PHP根据给定索引的匹配值合并数组 [英] PHP merge arrays based on matching value of a given index
本文介绍了PHP根据给定索引的匹配值合并数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个这样的数组:
Array1
Array
(
[0] => Array
(
[ID] => 101
[Code] => 1075
[Date] => 2012-03-03 17:13:12.433
)
[1] => Array
(
[ID] => 103
[Code] => 175
[Date] => 2012-09-05 20:30:02.217
)
[2] => Array
(
[ID] => 109
[Code] => 178
[Date] => 2012-07-05 20:30:02.217
)
)
Array2
Array
(
[0] => Array
(
[Amount] => 1234
[ID] => 101
)
[1] => Array
(
[Amount] => 1342
[ID] => 103
)
[2] => Array
(
[Amount] => 0
[ID] => 0
)
)
我使用此代码根据ID索引的匹配值将它们组合起来.
I use this code to combine them based on the matching values of the ID index.
$combined = array();
foreach ($arr as $arrs) {
$comb = array('ID' => $arrs['ID'], 'Code' => $arrs['Code'],'Date' => $arrs['Date'],'Amount' => '');
foreach ($arr4 as $arr2) {
if ($arr2['ID'] == $arrs['ID']) {
$comb['Amount'] = $arr2['Amount'];
break;
}
else {
$comb['Amount'] = $arr2['Amount'];
}
}
$combined[] = $comb;
}
echo print_r($combined);
这是我从这段代码中获得的期望输出:
And here is the desired output I get from this code :
Array
(
[0] => Array
(
[ID] => 101
[Code] => 1075
[Date] => 2012-03-03 17:13:12.433
[Amount] => 1234
)
[1] => Array
(
[ID] => 103
[Code] => 175
[Date] => 2012-09-05 20:30:02.217
[Amount] => 1342
)
[2] => Array
(
[ID] => 109
[Code] => 178
[Date] => 2012-07-05 20:30:02.217
[Amount] => 0
)
)
我想优化代码,使
$comb = array('ID' => $arrs['ID'], 'Code' => $arrs['Code'],'Date' => $arrs['Date'],'Amount' => '');
应该动态生成,而不是硬编码.
而不是$comb['Amount'] = $arr2['Amount'];
,我希望代码自动将所有其他字段添加到ID匹配的第一个数组中.
should be generated dynamically rather than hard coded.
And instead of $comb['Amount'] = $arr2['Amount'];
I want code to automatically add all the other feilds to the first array where the ID matches.
我该如何实现?
推荐答案
最简单的解决方案,使其完全动态地与ID
分开,如下所示:
Simplest solution to make it completely dynamic apart from ID
, do like below:
$arr2 = array_column($array2, "ID");
$finalArray = array();
foreach($array1 as $arr){
$key = array_search($arr['ID'], $arr2);
if($key ===false){
$key = array_search(0, $arr2);
}
unset($array2[$key]['ID']);
$finalArray[] = array_merge($arr,$array2[$key]);
}
print_r($finalArray);
这篇关于PHP根据给定索引的匹配值合并数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文