比较两个二维数组并找到特定列中的所有交集

问题描述 投票:0回答:1

我有两个数组,第一个是旧的,第二个是新的。 我想比较它们并仅输出重复项。

我尝试了一些痛苦的事情:

array_intersect
array_search
没有任何结果......

$oldArray = [
    ['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'],
];

$newArray = [
    ['id' => 'new_id_1', 'color' => 'blue'],
    ['id' => 'new_id_2', 'color' => 'pink'],
    ['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
php arrays multidimensional-array intersection
1个回答
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

通过 3v4l.org 尝试一下

© www.soinside.com 2019 - 2024. All rights reserved.