数组重组为树结构

array restructure to tree structure

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

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
    )

)

此处user4在user3用户中,user3在user2用户中包含其用户,user2在user1用户中包含其用户,user5在user1用户中

想要的结构

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()
                                                         )
                                                  )
                                           )
                                  )
                            )
                    )
             )
  )

试试这个

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