简体   繁体   English

如何在PHP中构建树?

[英]How to build a tree in PHP?

I have incoming POST array: 我有传入的POST数组:

$parameters = array("1" , "2" , "3", "4", "5");
$parents = array("null" , "1" , "1", "3", "3");
$values = array("A" , "B" , "C", "D", "E");

The number of $parameters is unlimited. $parameters的数量是无限的。

So, I need to build a tree with nested parameters. 因此,我需要构建带有嵌套参数的树。

The resulting output should be: 结果输出应为:

1 -> {2 => value, 3 -> {4 => value, 5 => value}}

I tried to use the below loop: 我尝试使用以下循环:

foreach ($parameters["parameters"] as $index => $id) {
   if(!is_null($parameters["parents"][$index])){
      $output[$parameters["parents"][$index]][] = $id;
   }
}

But it works only for one tree level, I think I need to use a recursive approach. 但这仅适用于一个树级别,我想我需要使用递归方法。

You can use an iterative approach by keeping the references of the root elements in the array() $refs . 通过将根元素的引用保留在array() $refs可以使用迭代方法。
The code here misses the value for the elements which have children - it's your requirement - but you can keep it using explicit keys in the resulting array - say value => ..., children => array() for example. 这里的代码缺少具有子元素的元素的值-这是您的要求-但您可以在结果array使用显式键来保留它的value => ..., children => array() -例如说value => ..., children => array()

$parameters = array('1', '2', '3', '4', '5');
$parents = array('null', '1', '1', '3', '3');
$values = array(    'A', 'B', 'C', 'D', 'E');

$tree = array();
$refs = array();
foreach ($parameters as $key=>$val) {
    if (isset($refs[$parents[$key]])) {
        if(!is_array($refs[$parents[$key]]))
            $refs[$parents[$key]] = array();
        $refs[$parents[$key]][$val] = $values[$key];
        $refs[$val] = &$refs[$parents[$key]][$val];
    } else {
        $tree[$val] = $values[$key];
        $refs[$val] = &$tree[$val];
    }
}

print_r($tree);

The above will print: 上面将打印:

Array
(
    [1] => Array
        (
            [2] => B
            [3] => Array
                (
                    [4] => D
                    [5] => E
                )
        )
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM