<?php
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);
?>
本作品採用《CC 協議》,轉載必須註明作者和本文連結