PHP将多维数组合并为一个

时间:2016-03-15 12:14:32

标签: php arrays multidimensional-array

我需要修改以下数组:

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
        )

)

有谁知道如何实现这个目标?

1 个答案:

答案 0 :(得分:1)

尝试 -

$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)
  }
}
支持 PHP {>} array_column()

array_combine()