2015-01-06 192 views
1

我在這個結構中包含一個包含用戶元素的數組,每個用戶都可以與另一個用戶相關。
我只想製作一棵樹,每個用戶都包含其子用戶,像樹一樣是陣列重構爲樹狀結構

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的用戶,用戶3包含其在用戶2的用戶的用戶,用戶2包含其在用戶1的用戶和USER5用戶在用戶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() 
                 ) 
               ) 
              ) 
           ) 
          ) 
        ) 
      ) 
) 
+0

請也寫陣列的你的願望輸出。 –

+0

並提供你已經試過的東西 – Ziumin

+0

@ShaifulIslam我做過 –

回答

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