我有两个数组,第一个数组为旧数组,第二个数组为新数组。 我想比较它们,只输出重复项。
我尝试一些痛苦的事情:array_intersect
和array_search
没有任何结果...
第一个数组(旧)包含作为输出:
[0] => Array (
[id] => old_id_1
[color] => red
)
[1] => Array (
[id] => old_id_2
[color] => blue
)
[2] => Array (
[id] => old_id_3
[color] => green
)
[3] => Array (
[id] => old_id_4
[color] => purple
)
[4] => Array (
[id] => old_id_5
[color] => yellow
)
第二个(新)输出:
[0] => Array (
[id] => new_id_1
[color] => blue
)
[1] => Array (
[id] => new_id_2
[color] => pink
)
[2] => Array (
[id] => new_id_3
[color] => purple
)
作为回报,我想做些类似的事情:
We find 2 duplicates colors :
- blue (new_id_1) in old_id_2
- purple (new_id_3) in old_id_4
如果有人有什么想法。
答案 0 :(得分:1)
尝试一下:
$firstArr = [
['id' => 'old_id_1', 'color' => 'red'],
['id' => 'old_id_2', 'color' => 'blue'],
['id' => 'old_id_3', 'color' => 'green'],
['id' => 'old_id_4', 'color' => 'purple'],
['id' => 'old_id_5', 'color' => 'yellow'],
];
$secondArr = [
['id' => 'new_id_1', 'color' => 'blue'],
['id' => 'new_id_2', 'color' => 'pink'],
['id' => 'new_id_3', 'color' => 'purple'],
];
$firstArrAssoc = array_combine(array_column($firstArr, 'color'), array_column($firstArr, 'id'));
$duplicatesArr = [];
foreach ($secondArr as $row) {
if (array_key_exists($row['color'], $firstArrAssoc)) {
$duplicatesArr[] = "- $row[color] ($row[id]) in {$firstArrAssoc[$row['color']]}";
}
}
echo "We find " . count($duplicatesArr) . " duplicates colors :\n";
echo implode("\n", $duplicatesArr);
输出:
We find 2 duplicates colors :
- blue (new_id_1) in old_id_2
- purple (new_id_3) in old_id_4