如果你对该文章中的内容有疑问/不解,可以点击此处链接提问
要注明问题和此文章链接地址 点击此处跳转
<code class=""><?php
/**
* $data 原始数据(二维数组)
* $parent_key 原始数据父级字段
* $child_key 生成子集的字段
*/
function treeArray($data,$parent_key,$child_key){
$tree = [];
foreach ($data as $key => $val) {
if ($val[$parent_key] == 0) {
$tree[] = &$data[$key];
} else {
$data[$val[$parent_key]][$child_key][] = &$data[$key];
}
}
return $tree;
}
$data = [
['id'=>1,'pid'=>0,'name'=>1],
['id'=>2,'pid'=>0,'name'=>2],
['id'=>3,'pid'=>1,'name'=>3],
['id'=>4,'pid'=>2,'name'=>4],
['id'=>5,'pid'=>3,'name'=>5],
['id'=>6,'pid'=>4,'name'=>6],
['id'=>7,'pid'=>5,'name'=>7],
['id'=>8,'pid'=>6,'name'=>8],
];
$tree = treeArray(array_column($data,null,'id'), 'pid','child');
print_r($tree);
?>
</code>