简体   繁体   English

数组作为数组PHP

[英]array to array as tree PHP

I have an array in php like that: 我在php中有这样的数组:

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

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

How can I create a tree from this array like this : 我怎样才能像这样从这个数组创建树:

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

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

that mean I want to display the Father and of below each father his son. 这意味着我想展示父亲,并在每个父亲下面展示他的儿子。 Thanks 谢谢

I would iterate trough the base array and create a new array with the fathers as indexes and all their children in an array. 我将遍历基本数组,并创建一个新数组,以父级为索引,并将所有子级作为数组。

The new array would look something like: 新数组如下所示:

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

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

Then, you could use a function like: 然后,您可以使用类似以下的功能:

$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); 
}

This will build the depth recursively no matter the depth. 无论深度如何,都会递归地构建深度。 Tested here: http://phptester.net/ 在这里测试: http//phptester.net/

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

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