2013-06-02 79 views
0

我有一個數組,看起來像:試圖使孩子數組下父母陣列出現重組的陣列

$someArray = array(
array(
    "id"=> 1, 
    "name"=> "somename1", 
    "parent"=> 0 
), 
array(
    "id"=> 53, 
    "name"=> "somename2", 
    "parent"=> 1 
), 
array(
    "id"=> 921, 
    "name"=> "somename3", 
    "parent"=> 53, 
) 
. 
. 
. 
. 
. 
. 
); 

離岸金融中心有更多的細胞在陣列中,這只是一小部分

我我試圖把這個數組變成類似的東西:

$someArray = array(
array(
    "id"=> 1, 
    "name"=> "somename1", 
    "parent"=> 0, 
    "children" => array(
     array(
      "id"=> 53, 
      "name"=> "somename2", 
      "parent"=> 1, 
      "children" => array(
       array(
        "id"=> 921, 
        "name"=> "somename3", 
        "parent"=> 53, 
        "children" => array(

        ) 
       ) 
      ) 
     ) 
    ) 
) 

. 
. 
. 
. 
. 
. 
); 

我試了一天半,似乎無法完成它。

謝謝先進。

回答

0
/* 
    Gets reversed array, 
    Returns multidimensional tree array. 
*/ 
function buildTree($parts) { 
    if (count($parts) == 1) { 
     return $parts[0]; 
    } 
    $last_item = array_pop($parts); 
    $last_item[] = buildTree($parts); 
    return $last_item; 
} 

測試:

$parts = array(
      array('1','2','3',5), 
      array('3','8','3',1), 
      array('1', 5,'2','3'), 
      array('D','2','3',5), 
      array('A','2','3',5) 
     ); 

var_dump(buildTree(array_reverse($parts))); 

輸出:

array(5) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> int(5) [4]=> array(5) { 
    [0]=> string(1) "3" [1]=> string(1) "8" [2]=> string(1) "3" [3]=> int(1) [4]=> array(5) { 
     [0]=> string(1) "1" [1]=> int(5) [2]=> string(1) "2" [3]=> string(1) "3" [4]=> array(5) { 
      [0]=> string(1) "D" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> int(5) [4]=> array(4) { 
       [0]=> string(1) "A" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> int(5) 
} } } } }