PHP合并条件数组 [英] PHP merge arrays with a condition
本文介绍了PHP合并条件数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个数组.我想将它们合并为1个数组,但要有条件.如果Ref和Id相等,则合并
I have 2 arrays. I would like to merge them into 1 array but with a condition. If Ref and Id are equal then merge
Array Number One
(
[0] => Array
(
[Id] => 60
[Name] => Water Authority
)
[1] => Array
(
[Id] => 63
[Name] => Service Station
)
Array Number Two
(
[0] => Array
(
[Date] => 2017-10-12
[Amount] => 130.00
[Ref] => 60
[Description] => Water Bill Oct
)
[1] => Array
(
[Date] => 2017-10-10
[Amount] => 130.00
[Ref] => 63
[Description] => Gas
)
[2] => Array
(
[Date] => 2017-09-17
[Amount] => 600.00
[Ref] => 60
[Description] => Water bill Sept
)
我想将它们合并在一起,所以最终得到:
I would like to merge them with so I end up with:
Merged Array
(
[0] => Array
(
[Date] => 2017-10-12
[Amount] => 130.00
[Ref] => 60
[Description] => Water Bill Oct
[Id] => 60
[Name] => Water Authority
)
[1] => Array
(
[Date] => 2017-10-10
[Amount] => 130.00
[Ref] => 63
[Description] => Gas
[Id] => 63
[Name] => Service Station
)
and so on...
我该怎么做?我尝试了array_merge,但我知道它还需要其他东西,只是不知道什么!
How would I do that? I tried array_merge but I know it needs something else, just don't know what!
推荐答案
假设第一个数组为$ array1,第二个数组为array2
Let assume first array be as $array1, second array be array2
$ result = [];
$result = [];
foreach ($array1 as $key1 => $value1) {
foreach ($array2 as $key2 => $value2) {
if ($value1['Id']==$value2['Ref']) {
$result[]=$value2+$value1;
}
}
}
结果将与您预期的一样
这篇关于PHP合并条件数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文