[英]array restructure to tree structure
I have an array in this structure that contains elements of users, every user can be related to another user. 我在此结构中有一个包含用户元素的数组,每个用户都可以与另一个用户相关。
I just want to make a tree of users that every user contains its child users to be like a 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
)
) )
Here user4 in user3 users, user3 contains its users in user2 users, user2 contains its users in user1 users and user5 in user1 users 这里的user4在user3用户中,user3在user2用户中包含其用户,user2在user1用户中包含其用户,在user1用户中包含user5
The desired structure to be like 所需的结构像
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()
)
)
)
)
)
)
)
)
Try this 尝试这个
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;
}
Now write following code 现在编写以下代码
//$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
Even you can do it simple using following code 甚至您也可以使用以下代码来简化操作
$root_user=get_child(null,$users);
print_r($root_user);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.