【问题标题】:array to array as tree PHP数组到数组为树 PHP
【发布时间】:2016-03-29 16:10:03
【问题描述】:

我在 php 中有一个这样的数组:

Array
(
    [0] => Array
        (
            [ref] => a
            [ref_father] => 0
        )

    [1] => Array
        (
            [ref] => b
            [ref_father] => 0
        )
    [2] => Array
        (
            [ref] => c
            [ref_father] => a
        )

我怎样才能像这样从这个数组中创建一棵树:

Array
(
    [0] => Array
        (
            [ref] => a
            [ref_father] => 0
        )

    [1] => Array
        (
            [ref] => c
            [ref_father] => a
        )
    [2] => Array
        (
            [ref] => b
            [ref_father] => 0
        )

这意味着我想在每个父亲下面展示他的儿子。谢谢

【问题讨论】:

  • 使用二维数组数据结构来表示树形结构在一般意义上是行不通的。它可以在有限的情况下工作,例如表示堆,但通常您会希望使用树数据结构来表示树。
  • @MikyDinescu: 如果我有一维数组数据结构??
  • 一维数组不足以表示一棵树。

标签: php recursion tree


【解决方案1】:

我将遍历基本数组并创建一个新数组,其中父亲作为索引,并将其所有孩子放在一个数组中。

新数组看起来像:

Array
(
    [0] => Array('a', 'b') // 0 Is the base root
    ['a'] => Array('c')

    ['b'] => Array ()
    ['c'] => Array()

然后,您可以使用如下函数:

$a = array(
    0 => array('a', 'b'),
    'a' => array('c'),
    'b' => array(),
    'c' => array()
);

$depth_array = array();

function build_depth($key, $mapped_array) {
    if (array_key_exists($key, $mapped_array)) {
        if ( count($mapped_array[$key]) == 0 ) return array();
        else {
            foreach( $mapped_array[$key] as $child ) {
                return array($child => build_depth($child, $mapped_array));
            }
        }
    }
}

foreach ( $a[0] as $root_child ) {
    $depth_array[$root_child] = build_depth($root_child, $a); 
}

无论深度如何,这都会递归地构建深度。 在这里测试: http://phptester.net/

【讨论】:

    猜你喜欢
    • 2014-02-04
    • 1970-01-01
    • 2012-02-02
    • 2014-10-30
    • 2011-05-18
    • 2018-08-03
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    相关资源
    最近更新 更多