PHP-多维数组合并到一个数组

时间:2019-05-22 10:27:54

标签: php arrays multidimensional-array array-merge

我有2个这样的数组:

数组一:

[
    [
        "id" => 1234
        "name" => "John"
    ],
    [
        "id" => 1235
        "name" => "doe"
    ]
]

第二个数组:

[
    [
        "age" => 12
    ],
    [
        "age" => 13
    ]
]

我已经尝试过使用array_reducearray_maparray_merge_recursive并将其组合在一起,但是结果仍然不匹配。

如何使两个数组如下所示?

[
    [
        "id" => 1234
        "name" => "John"
        "age" => 12
    ],
    [
        "id" => 1235
        "name" => "doe"
        "age" => 13
    ]
]

请帮助我。谢谢

3 个答案:

答案 0 :(得分:6)

array-maparray-merge的组合应该可以解决问题:

$c = array_map('array_merge', $a, $b);

实时示例:3v4l

答案 1 :(得分:1)

您可以像这样使用array_merge:

<?php

$array = array(
                  ["id" => "1",  
                   "name" => "denba"
                 ],

                    ["id" => "1",  
                   "name" => "chpa7"
                 ],

              );              

$ages = array(
                  ["age" => "15",  

                 ],

                    ["age" => "17", 
                 ],

              );

foreach($array as $key => $value){
    $array[$key]=array_merge($array[$key], $ages[$key]);
}


var_dump($array); 
/*output:
    array(2) {
  [0]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["name"]=>
    string(5) "denba"
    ["age"]=>
    string(2) "15"
  }
  [1]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["name"]=>
    string(5) "chpa7"
    ["age"]=>
    string(2) "17"
  }
}
*/

答案 2 :(得分:0)

Demo link

您可以迭代第一个数组,并在尊重索引匹配的情况下与第二个数组合并

$merged =[];
foreach($a as $k => $val){
    array_push($merged,array_merge($val,$b[$k]));
}
print_r($merged);