php 两个数组怎么合并成一个数组

红蜻蜓
  • 99
$a= [
       ['id'=>1,'age'=>12],
       ['id'=>2,'age'=>13],
       ['id'=>3,'age'=>15]
];
$b= [
        ['id'=>1,'money'=>100],
        ['id'=>3,'money'=>400],  
        ['id'=>2,'money'=>200]
];

怎么按照id值匹配合并到一个数组中,形成这样。

$c=[
       ['id'=>1,'age'=>12,'money'=>100],
       ['id'=>2,'age'=>13,'money'=>200],
       ['id'=>3,'age'=>15,'money'=>400] 
];  
回复
阅读 1.5k
4 个回答
✓ 已被采纳
$a = [
  ['id' => 1, 'age' => 12],
  ['id' => 2, 'age' => 13],
  ['id' => 3, 'age' => 15]
];

$b = [
  ['id' => 1, 'money' => 100],
  ['id' => 2, 'money' => 200],
  ['id' => 3, 'money' => 400],
];

$c = [];

foreach ($a as $_a) {
  $_c = $_a;
  foreach ($b as $_b) {
    if ($_a['id'] === $_b['id']) {
      $_c['money'] = $_b['money'];
    }
  }
  $c[] = $_c;
}

print_r($c);

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

    $a= [
           ['id'=>1,'age'=>12],
           ['id'=>2,'age'=>13],
           ['id'=>3,'age'=>15]
    ];

    $b= [
            ['id'=>1,'money'=>100],
            ['id'=>3,'money'=>400],
            ['id'=>2,'money'=>200]
    ];
    $res_id_a = array_column($a,null,'id');
    $res_id_b = array_column($b,null,'id');
    foreach($res_id_a as $key => &$val){
        $val['money'] = $res_id_b[$key]['money'];
    }
    var_dump($res_id_a);die();

可以考虑array_map

你知道吗?

宣传栏