数组重组为树结构


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

在用户 3 用户中,user3 在用户 2 用户中包含其用户,user2 在用户 1 用户中包含其用户,用户 5 在用户 1 用户中

所需的结构

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