2014-02-25 161 views
0

我搜索一個解決方案將數組轉換爲另一個數組。我有這樣的一個:PHP:轉換多維數組

Array 
(
    [Germany] => Array 
     (
      [0] => Munich 
      [1] => Frankfurt 
     ) 

    [France] => Array 
     (
      [0] => Paris 
      [1] => Marseille 
      [2] => Lille 
      [3] => Starsbourg 
      [4] => Lyon 
      [5] => Bordeaux 
      [6] => Toulouse 
     ) 

    [Spain] => Array 
    (
     [0] => Madrid 
     [1] => Barcelona 
     [2] => Valencia 
    ) 
) 

什麼是它轉換到這個請最好的方式(與array_filter例如,或任何其他PHP函數):

Array 
(
    [0] => Array 
     (
      [value] => Germany 
      [cities] => Array 
       (
        [0] => Munich 
        [1] => Frankfurt 
       ) 
     ) 

    [1] => Array 
     (
      [value] => France 
      [cities] => Array 
       (
        [0] => Paris 
        [1] => Marseille 
        [2] => Lille 
        [3] => Starsbourg 
        [4] => Lyon 
        [5] => Bordeaux 
        [6] => Toulouse 
       ) 
     ) 

    [0] => Array 
     (
      [value] => Spain 
      [cities] => Array 
       (
        [0] => Madrid 
        [1] => Barcelona 
        [2] => Valencia 
       ) 
     ) 

) 

回答

2
$new_array = array(); 
foreach ($old_array as $country => $cities) 
{ 
    $new_array[] = array(
     'value' => $country, 
     'cities' => $cities 
    ); 
} 

應該做的工作。

+0

我的回答並不是很好@火箭一hazmat考慮你的問題,但我希望它更容易閱讀和理解:) –

+0

這麼簡單,對我很恥辱:D謝謝! – ncrocfer

+0

@MARTINDamien:我不知道。我想我更喜歡這個:-) –

2

你可以使用array_map

$newArray = array_map(function($key, $val){ 
    return array(
     'value' => $key, 
     'cities' => $val 
    ); 
}, array_keys($oldArray), $oldArray);