如何将多维数组转换为一维数组?

时间:2015-04-04 06:21:47

标签: php arrays algorithm multidimensional-array

我有这种格式的数组:

 Array ( [0] => Array ( [PRODUCT_ID] => 40 ) [1] => Array ( [QUANTITY] => 2 ) [2] => Array ( [PIECE_BAG] => 3 ) [3] => Array ( [TOTAL_QUANTITY] => 2 ) [4] => Array ( [UNIT_PRICE] => 3 ) [5] => Array ( [TOTAL_PRICE] => 6 ) [6] => Array ( [AVAILABILITY] => 4 ) )

我想要:

Array (  [PRODUCT_ID] => 40 [QUANTITY] => 2)

1 个答案:

答案 0 :(得分:1)

您需要先$array[0]$array[1]进行迭代,然后在foreach循环中获取所需的值。见代码:

<?php
$array = Array (
 0 => Array ( 'PRODUCT_ID' => 40 ),
 1 => Array ( 'QUANTITY' => 2 ),
 2 => Array ( 'PIECE_BAG' => 3 ),
 3 => Array ( 'TOTAL_QUANTITY' => 2 ),
 4 => Array ( 'UNIT_PRICE' => 3 ),
 5 => Array ( 'TOTAL_PRICE' => 6 ),
 6 => Array ( 'AVAILABILITY' => 4 ) );

$new_array = array();

for($i = 0; $i < 2; $i++) {
  foreach($array[$i] as $key => $value) {
    $new_array[$key] = $value;
  }  
} 

print_r($new_array);

输出:

Array
(
    [PRODUCT_ID] => 40
    [QUANTITY] => 2
)