2016-03-15 240 views
-3

我需要修改以下數組:PHP合併多維數組到一個

Array 
(
    [category_id] => Array 
     (
      [0] => 21 
      [1] => 22 
     ) 

    [amount] => Array 
     (
      [0] => 10000 
      [1] => 2000 
     ) 

) 

我需要得到的輸出看起來像這樣:

Array 
(
    [0] => Array 
     (
      [category_id] => 21 
      [amount] => 10000 
     ) 

    [1] => Array 
     (
      [category_id] => 22 
      [amount] => 2000 
     ) 

) 

有誰知道如何實現這一目標?

+0

這是基本的數組操作。你嘗試過什麼嗎? – axiac

回答

1

TRY -

$array = array 
(
    'category_id' => array 
     (
      '0' => 21, 
      '1' => 22 
     ), 

    'amount' => array 
     (
      '0' => 10000, 
      '1' => 2000 
     ) 

); 

$new = array(); 

$keys = array_keys($array); 
$elements = 2; 

for($i = 0; $i < 2; $i++) { 
    $temp = array_column($array, $i); 
    $new[] = array_combine($keys, $temp); 
} 

var_dump($new); 

輸出

array(2) { 
    [0]=> 
    array(2) { 
    ["category_id"]=> 
    int(21) 
    ["amount"]=> 
    int(10000) 
    } 
    [1]=> 
    array(2) { 
    ["category_id"]=> 
    int(22) 
    ["amount"]=> 
    int(2000) 
    } 
} 

array_column()支持PHP> = 5.5

array_combine()

Fiddle