/**
* $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);
数据库设计跟数组格式一样即可。这个应该很简单,很容易理解。