如下两个数组 ,求一个最佳的合并方法
$arr_1 = [
['id'=>1,'cc'=>'dd','ee'=>'hh'],
['id'=>2,'cc'=>'gg','ee'=>'qq'],
['id'=>3,'cc'=>'yy','ee'=>'!!'],
];
$arr_2 = [
['id'=>2,'hh'=>'##','ll'=>'^^'],
['id'=>1,'hh'=>'@@','ll'=>'%%'],
['id'=>4,'hh'=>'$$','ll'=>'&&'],
];
$arr = [];
foreach ($arr_1 as $key => &$value) {
foreach ($arr_2 as $k => $item) {
if ($value['id'] === $item['id']) {
$temp = array_merge($value,$item);
$arr[] = $temp;
}
}
}
$temp_ids = array_column($arr, 'id');
$sub_1 = array_filter($arr_1,function($o) use ($temp_ids){
if (!in_array($o['id'], $temp_ids)) {
return true;
}
});
$sub_2 = array_filter($arr_2,function($i) use ($temp_ids){
if (!in_array($i['id'], $temp_ids)) {
return true;
}
});
$res = array_merge($arr,$sub_1,$sub_2);
echo json_encode($res);
exit;
结果
[{"id":1,"cc":"dd","ee":"hh","hh":"@@","ll":"%%"},{"id":2,"cc":"gg","ee":"qq","hh":"##","ll":"^^"},{"id":3,"cc":"yy","ee":"\uff01\uff01"},{"id":4,"hh":"$$","ll":"&&"}]
实际上作者那样写也挺不错了
如果想要使用有气势的排比句可以这样