2014-09-29 59 views
1

我有一個這樣的數組。PHP - 展平陣列

Array 
(
    [0] => Array 
     (
      [category] => vegetable 
      [type] => garden 
      [children] => Array 
       (
        [0] => Array 
         (
          [name] => cabbage 
         ) 

        [1] => Array 
         (
          [name] => eggplant 
         ) 

       ) 

     ) 
    [1] => Array 
     (
      [category] => fruit 
      [type] => citrus 
     ) 
) 

什麼是一種簡單的方法來構建這樣使用PHP的結果數組?

Array 
(
    [0] => Array 
     (
      [category] => vegetable 
      [type] => garden 
      [name] => cabbage 
     ) 
    [1] => Array 
     (
      [category] => vegetable 
      [type] => garden 
      [name] => eggplant 
     ) 
    [2] => Array 
     (
      [category] => fruit 
      [type] => citrus 
     ) 
) 

我目前正在爲此解決方案。

+1

的可能重複[如何 「扁平化」 的多維數組簡單的在PHP?](http://stackoverflow.com/questions/526556/how-以平面多維陣列到簡單的一個在php) – 2014-09-29 19:57:46

+0

@MarinAtanasov這似乎並不是一個案例。那裏沒有關聯數組。 – 2014-09-29 20:03:06

回答

1

也許不是'美'的方式,但只是像這樣?

$newArray = array();  

foreach($currentArray as $item) 
{ 
    if(!empty($item['children']) && is_array($item['children'])) 
    { 
     foreach($item['children'] as $children) 
     { 
      $newArray[] = array('category'=>$item['category'] , 'type'=>$item['type'] , 'name'=>$children['name']); 
     } 
    } 
    else 
    { 
     $newArray[] = array('category'=>$item['category'] , 'type'=>$item['type']); 
    } 
} 
+0

這很好用。謝謝 – Jake 2014-09-29 20:14:44

1

你需要children在你的層次?

<?php 

function transform_impl($arr, $obj, &$res) { 
    $res = array(); 
    foreach ($arr as $item) { 
     $children = @$item['children']; 
     unset($item['children']); 
     $res[] = array_merge($obj, $item); 
     if ($children) { 
      transform_impl($children, array_merge($obj, $item), $res); 
     } 
    } 
} 

function transform($arr) { 
    $res = array(); 
    transform_impl($arr, array(), $res); 
    return $res; 
} 

print_r(transform(array(
    array("category" => "vegetable", "type" => "garden", "children" => 
     array(array("name" => "cabbage"), array("name" => "eggplant")) 
    ), 
    array("category" => "fruit", "type" => "citrus") 
))); 

直播版本:http://ideone.com/0wO4wU