【问题标题】:gettting child tree from main tree php从主树php获取子树
【发布时间】:2020-02-21 10:42:54
【问题描述】:

我已经从平面 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


【解决方案1】:
<?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($user_id, array_column($data, 'id'));
$new = array();
foreach ($flat as $a){
    $new[$a['parent_id']][] = $a;
}
$tree = createTree($new, array($data[$index]));
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

【讨论】:

  • 这是将整个数组转换为树,我需要从整个树中获取任何特定的树
  • 非常感谢,我合并两个答案并得到我的结果。
  • 您可以编辑我的答案,以便将来对其他人有所帮助。
【解决方案2】:
<?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]);

?>

一个想法:

既然你自己构建数组,为什么不考虑类似的结构

$flat[$parent_id][] = [
   'id' => $child_id,
   'name' => $child_name
];

然后您可以从主树中获取子树,如下所示

$child_tree = $flat[$parent_id];

【讨论】:

  • 感谢它帮助我找到 ID 的索引,并使用下面的答案使用索引来绘制我的树。
猜你喜欢
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
  • 2018-06-18
  • 2014-06-13
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
相关资源
最近更新 更多