2014-12-03 157 views
0

我的數組看起來像。我試圖將其轉換爲單個關聯數組,該數組將包含所有嵌套數組的嵌套關鍵字。將嵌套數組轉換爲關聯數組

array(
    (int) 0 => array(
     'Size' => array(
      'id' => '12', 
      'name' => 'Mini' 
     ), 
     'Price' => array(
      'price' => '4.35' 
     ) 
    ), 
    (int) 1 => array(
     'Size' => array(
      'id' => '13', 
      'name' => 'Medium' 
     ), 
     'Price' => array(
      'price' => '6.15' 
     ) 
    ), 
    (int) 2 => array(
     'Size' => array(
      'id' => '15', 
      'name' => 'Maxi' 
     ), 
     'Price' => array(
      'price' => '11.75' 
     ) 
    ) 
) 

是否有任何可用的函數,它接受這個陣列中創建一個新的類似

array(
     (int) 0 => array(
       'id' => '12', 
       'name' => 'Mini' 
       'price' => '4.35' 
      ), 
      ..., 
      ... 
     ) 

回答

1
$new_array = array(); 
foreach($array as $key=>$data) { 
    $new_array[$key] = array_reduce($data,'array_merge',array()); 
} 

echo '<pre>'; 
print_r($new_array); 
echo '</pre>'; 

http://codepad.viper-7.com/vclE9v

0

$result = array_map($source_array, function ($item){ return array_flatten($item); });

2

你可以在這種情況下使用call_user_func_array()

$new_array = array(); 
foreach($array as $values) { 
    $new_array[] = call_user_func_array('array_merge', $values); 
} 

echo '<pre>'; 
print_r($new_array); 

Sample Output

1

對於這個特定的陣列可以使用這樣的事情:

$newArray = array(); 
foreach($array as $key => $arrayItem) 
{ 
    $newArray[$key]['id'] = $arrayItem['Size']['id']; 
    $newArray[$key]['name'] = $arrayItem['Size']['name']; 
    $newArray[$key]['price'] = $arrayItem['Price']['price']; 
} 
1

試試這個代碼

$test = array(
(int) 0 => array(
    'Size' => array(
     'id' => '12', 
     'name' => 'Mini' 
    ), 
    'Price' => array(
     'price' => '4.35' 
    ) 
), 
(int) 1 => array(
    'Size' => array(
     'id' => '13', 
     'name' => 'Medium' 
    ), 
    'Price' => array(
     'price' => '6.15' 
    ) 
), 
(int) 2 => array(
    'Size' => array(
     'id' => '15', 
     'name' => 'Maxi' 
    ), 
    'Price' => array(
     'price' => '11.75' 
    ) 
) 
); 
$result = array(); 
$i=0; 
foreach ($test as $temp){ 

$result[$i] = array(
     'id' => $temp['Size']['id'], 
     'name' => $temp['Size']['name'], 
     'price' => $temp['Price']['price'] 
    ); 

$i++; 
} 
echo "<pre/>"; 
print_r($result);