在PHP中按ID组合两个数组 [英] Combining two arrays by ID in PHP
问题描述
我需要比较PHP中的两个2D数组。数组如下所示:
I need to compare two 2D arrays in PHP. The arrays look like this:
Array one
ID Name
11 Aa
11 Ab
12 Bb
13 Cc
14 Dd
15 Ee
Array two
ID Content
11 Cat
13 Dog
14 Donkey
现在我需要将两者合并成一个数组
Now I'd need to combine these two into an array like this:
ID Name Conent
11 Aa Cat
11 Ab Cat
12 Bb
13 Cc Dog
14 Dd Donkey
15 Ee
如何我做到了吗?我对array_merge()或$ array3 = $ array1 + $ array2;没有运气。
How can I accomplish this? I have had no luck with array_merge() or $array3 = $array1 + $array2;
推荐答案
一种快速方法是遍历第一个数组并附加第二个数组的值:
A quick way would be to iterate over the first array and append the value from the second:
$array1 = array('11' => 'Aa', '12' => 'Bb', '13' => 'Cc', '14' => 'Dd', '15' => 'Ee');
$array2 = array('11' => 'Cat', '13' => 'Dog', '14' => 'Donkey');
$combined = array();
foreach ($array1 as $key => $val) {
$combined[$key] = $val . (isset($array2[$key]) ? ' '.$array2[$key] : '');
}
这将循环遍历 $中的每个键/值array1
并将其添加到 $ combined
数组中。如果 $ array2
中的值存在相同的索引,它将把它附加到 $ array1
中的那个值上,并分开
This will loop through every key/value in $array1
and add it to the $combined
array. If a value in $array2
exists with the same index, it will append it to that value from $array1
, separated with a space.
更新:我误读了数组的格式(再次)。我假设 ID
是数组中的实际索引,但是作为示例,数组输出同时具有 Name
和 Content
,我假设 ID
是实际的索引字符串值,而不是数组本身的索引。要坚持使用循环方案,您可以迭代第一个数组,而嵌套循环遍历第二个数组:
UPDATE: I misread the format of the arrays (again). I assumed ID
was the actual index in the array, but as the example array output has both Name
and Content
, I'm assuming ID
is an actual index string value and not the index in the array itself. To stick with the loop scenario, you can iterate through the first array and have a nested loop iterate through the second:
$array1 = array(
array('ID' => '11', 'Name' => 'Aa'),
array('ID' => '12', 'Name' => 'Bb'),
array('ID' => '13', 'Name' => 'Cc'),
array('ID' => '14', 'Name' => 'Dd'),
array('ID' => '15', 'Name' => 'Ee'),
);
$array2 = array(
array('ID' => '11', 'Content' => 'Cat'),
array('ID' => '13', 'Content' => 'Dog'),
array('ID' => '14', 'Content' => 'Donkey')
);
$combined = array();
foreach ($array1 as $arr) {
$comb = array('ID' => $arr['ID'], 'Name' => $arr['Name'], 'Content' => '');
foreach ($array2 as $arr2) {
if ($arr2['ID'] == $arr['ID']) {
$comb['Content'] = $arr2['Content'];
break;
}
}
$combined[] = $comb;
}
这将添加 $ array1中的每个值
到组合数组,且仅当且仅当 $ array2
中的值包含相同的 ID
字段也会将它的 Content
字段也添加到数组中。这可以扩展为处理任何数量的字段,无论是按名称还是通过更改inner-if块以使 $ comb + = $ arr2;
代替(其中应该合并所有不存在的索引。)
This will add every value in $array1
to the combined array and if, and only if, a value in $array2
contains the same ID
field will it add it's Content
field to the array too. This can be extended to handle any number of fields as well, either by name, or by changing the inner-if block to have $comb += $arr2;
instead (which should merge all non-existing indexes).
这篇关于在PHP中按ID组合两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!