2013-02-12 67 views
0

我想創建嵌套數組平板陣列,像這樣的:嵌套數組持平PARENT_ID創建

[0]=>Array(
    "id"=>1, 
    "positions">Array(
    [0]=>Array(
     "id"=>2 
    ), 
    [1]=>Array(
     "id"=>3 
     "positions"=>Array(
     [0]=>Array(
     "id"=>4 
     ) 
    ) 
    ) 

是這樣的:

[0]=>Array(
    "id"=>1, 
    "parent_id"=>0 
), 
[1]=>Array(
    "id"=>2, 
    "parent_id"=>1 
), 
[2]=>Array(
    "id"=>3, 
    "parent_id"=>1 
), 
[3]=>Array(
    "id"=>4, 
    "parent_id"=>3 
) 

我沒有在PARENT_ID嵌套結構,所以所有的技巧都是通過嵌套數組「騎」,並根據父節點的id添加'parent_id'。我知道如何平整數組,但我需要parent_id信息。

+1

你的陣列是不正常的結構沒有終點爲某些陣列,加上完整的陣列 – 2013-02-12 12:40:30

回答

3

試試下面的代碼:我希望對大家有用吧...

<?php 

$array = array(array(
    "id"=>1, 
    "positions" => 
    array(
     array(
     "id"=>2 
     ), 
     array(
      "id"=>3, 
      "positions"=> 
       array(
        array(
        "id"=>4 
       ) 
       ) 
     ) 
    ) 
)); 

echo "<pre>"; 
print_r(getArray($array)); 
echo "</pre>"; 
exit; 


function getArray($array,$parent_id = 0) 
{ 
    $result = array(); 
    foreach ($array as $value) 
    { 
     $tmp = array(); 
     $tmp['id'] = $value['id']; 
     $tmp['parent_id'] = $parent_id;   
     $result[] = $tmp; 
     if(!empty($value['positions'])) 
     { 
      $result= array_merge($result,getArray($value['positions'],$value['id'])); 
     } 

    } 

    return $result; 


} 

?> 

OUTPUT:

Array 
(
    [0] => Array 
     (
      [id] => 1 
      [parent_id] => 0 
     ) 

    [1] => Array 
     (
      [id] => 2 
      [parent_id] => 1 
     ) 

    [2] => Array 
     (
      [id] => 3 
      [parent_id] => 1 
     ) 

    [3] => Array 
     (
      [id] => 4 
      [parent_id] => 3 
     ) 

) 
+0

+1快速回答 – 2013-02-12 12:58:29

1

使用此代碼

$result = array(); 
function generateArray($array,$parent=0){ 
    foreach ($array as $key=>$val){ 
     $tmp = array(); 
     if(!empty($val['id'])){ 
      $tmp['id'] = $val['id']; 
      $tmp['parent_id'] = $parent; 
      $result[] = $tmp; 
     } 
     if(!empty($val['positions'])){ 
      $result=array_merge($result,generateArray($val['positions'],$val['id'])); 
     } 
    } 
    return $result; 
} 

你的數組必須是這種結構的

$data = array(0=>array("id"=>1,"positions"=>array(0=>array("id"=>2),1=>array("id"=>3,"positions"=>array(0=>array("id"=>4)))))); 

然後調用函數generateArray()

var_dump(generateArray($data)); 
+0

$ VAL [「身份證」]永遠陣列,所以你的答案錯誤,請糾正它.... – Chintan 2013-02-12 13:34:51