从主树php获取子树

问题描述 投票:0回答:2

我已经从平面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 tree treeview
2个回答
0
投票
<?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;
}

check demo


0
投票
<?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]);

?>
© www.soinside.com 2019 - 2024. All rights reserved.