数组重组为树结构

时间:2015-01-06 16:13:29

标签: php arrays tree

我在这个结构中有一个包含用户元素的数组,每个用户都可以与另一个用户相关 我只想制作一个用户树,每个用户都包含其子用户就像一棵树。

Array
(
[0] => Array
    (
        [username] => user1
        [parent_user] => null
    )

[1] => Array
    (
        [username] => user2
        [parent_user] => user1
    )

[2] => Array
    (
        [username] => user3
        [parent_user] => user2
    )

[3] => Array
    (
        [username] => user4
        [parent_user] => user3
    )

[4] => Array
    (
        [username] => user5
        [parent_user] => null
    )

user3用户中的user4,user3包含user2用户中的用户,user2包含user1用户中的用户和user1用户中的user5

理想的结构

array(
[username] => user1
[users] => array(
           [0] => array(
                  username => user5
                  users => array()
                  )
           [1] => array(
                  username => user2
                  users => array(
                           [0] => array(
                                  username => user3
                                  users => array(
                                           [0] => array(
                                                  [0] => array(
                                                         username => user4
                                                         users => array()
                                                         )
                                                  )
                                           )
                                  )
                            )
                    )
             )
  )

1 个答案:

答案 0 :(得分:0)

试试这个

function get_child($parent,$users)//a function for recursive call
{
    $child=array();
    foreach($users as $user)
    {
        if($user['parent_user']==$parent)
        {
            $child[]=array("username"=>$user['username']);
        }
    }
    if(sizeof($child)>0)
    {
        foreach($child as &$c)
        {
            $c['users']=get_child($c['username'],$users);
        }
    }
    return $child;
}

现在编写以下代码

//$users //lets assume your main array name $users

    $root_user=array();
    foreach($users as $user)
    {
        if($user['parent_user']==null)
        {
            $root_user[]=array("username"=>$user['username']);
        }
    }

    foreach($root_user as &$user)
    {
        $user['users']=get_child($user['username'],$users);
    }

   print_r($root_user);//now print out the root_user which contains your desired result

即使您可以使用以下代码

轻松完成
$root_user=get_child(null,$users);
print_r($root_user);