我已经从平面php数组创建了一棵树,现在我想从主树中获取子树,我想传递子ID并获取子项的树
$flat = [
['id' => 100, 'parent_id' => 0, 'name' => 'root'],
['id' => 101, 'parent_id' => 100, 'name' => 'ch-1'],
['id' => 102, 'parent_id' => 101, 'name' => 'ch-1-1'],
['id' => 103, 'parent_id' => 101, 'name' => 'ch-1-2'],
['id' => 104, 'parent_id' => 101, 'name' => 'ch-1-2'],
['id' => 105, 'parent_id' => 104, 'name' => 'ch-1-2'],
['id' => 106, 'parent_id' => 101, 'name' => 'ch-1-2'],
['id' => 107, 'parent_id' => 101, 'name' => 'ch-1-2'],
];
$tree = getchildtree($flat, '101');
print_r($tree);
<?php
$flat = [
['id' => 100, 'parent_id' => 0, 'name' => 'root'],
['id' => 101, 'parent_id' => 100, 'name' => 'ch-1'],
['id' => 102, 'parent_id' => 101, 'name' => 'ch-1-1'],
['id' => 103, 'parent_id' => 101, 'name' => 'ch-1-2'],
['id' => 104, 'parent_id' => 101, 'name' => 'ch-1-2'],
['id' => 105, 'parent_id' => 104, 'name' => 'ch-1-2'],
['id' => 106, 'parent_id' => 101, 'name' => 'ch-1-2'],
['id' => 107, 'parent_id' => 101, 'name' => 'ch-1-2'],
];
$new = array();
foreach ($flat as $a){
$new[$a['parent_id']][] = $a;
}
$tree = createTree($new, array($flat[0]));
print_r($tree);
function createTree(&$list, $parent){
$tree = array();
foreach ($parent as $k=>$l){
if(isset($list[$l['id']])){
$l['children'] = createTree($list, $list[$l['id']]);
}
$tree[] = $l;
}
return $tree;
}
<?php
$flat = [
['id' => 100, 'parent_id' => 0, 'name' => 'root'],
['id' => 101, 'parent_id' => 100, 'name' => 'ch-1'],
['id' => 102, 'parent_id' => 101, 'name' => 'ch-1-1'],
['id' => 103, 'parent_id' => 101, 'name' => 'ch-1-2'],
['id' => 104, 'parent_id' => 101, 'name' => 'ch-1-2'],
['id' => 105, 'parent_id' => 104, 'name' => 'ch-1-2'],
['id' => 106, 'parent_id' => 101, 'name' => 'ch-1-2'],
['id' => 107, 'parent_id' => 101, 'name' => 'ch-1-2'],
];
$index = array_search(101, array_column($flat, 'parent_id'));
var_dump($flat[$index]);
?>