首页 > 解决方案 > 在删除重复项时合并两个多维数组,依赖于它们的特定元素

问题描述

我正在研究Facebook API. 我有这个数组:

["data"] => Array(31) {
    [0] => Array(6) {
        ["id"] => String(13) "6003110325672"
        ["name"] => String(17) "Cristiano Ronaldo"
        ["audience_size"] => Integer  122006620
        ["path"] => Array(3) {
            [0] => String(9) "Interessi"
            [1] => String(20) "Interessi aggiuntivi"
            [2] => String(17) "Cristiano Ronaldo"
        }
        ["description"] => NULL
        ["topic"] => String(6) "People"
    }
    [1] => Array(6) {
        ["id"] => String(13) "6003114817426"
        ["name"] => String(10) "Ronaldinho"
        ["audience_size"] => Integer  17910990
        ["path"] => Array(3) {
            [0] => String(9) "Interessi"
            [1] => String(20) "Interessi aggiuntivi"
            [2] => String(10) "Ronaldinho"
        }
        ["description"] => NULL
        ["topic"] => String(6) "People"
    }

继续使用其他索引。然后我得到了这个:

["data"] => Array(45) {
    [0] => Array(11) {
        ["id"] => String(13) "6003129962717"
        ["name"] => String(16) "Zinédine Zidane"
        ["type"] => NULL
        ["path"] => NULL
        ["description"] => NULL
        ["source"] => NULL
        ["partner"] => NULL
        ["audience_size"] => Integer  14137830
        ["country"] => NULL
        ["country_access"] => NULL
        ["topic"] => NULL
    }
    [1] => Array(11) {
        ["id"] => String(13) "6003115921142"
        ["name"] => String(13) "Thierry Henry"
        ["type"] => NULL
        ["path"] => NULL
        ["description"] => NULL
        ["source"] => NULL
        ["partner"] => NULL
        ["audience_size"] => Integer  2601710
        ["country"] => NULL
        ["country_access"] => NULL
        ["topic"] => NULL
    }
    [2] => Array(11) {
        ["id"] => String(13) "6003114817426"
        ["name"] => String(10) "Ronaldinho"
        ["type"] => NULL
        ["path"] => NULL
        ["description"] => NULL
        ["source"] => NULL
        ["partner"] => NULL
        ["audience_size"] => Integer  17910990
        ["country"] => NULL
        ["country_access"] => NULL
        ["topic"] => NULL
    }

作为第一个,继续附加索引。

首先,我尝试使用 合并数组array_merge(),但没有成功,因为我丢失了其中的部分数据。所以我想正确地合并它们。然后,我注意到在第二个中,我将“Ronaldinho”元素作为重复项(2nd array index 21st array index 1)。我几乎尝试了所有方法来弄清楚如何删除合并中的第一个或第二个,但PHP每次都用错误和警告回复我。

我的目标是将两个数组合二为一,根据“名称”元素删除重复项。

我感谢任何可以帮助我的人,我被困住了。

标签: phparraysduplicates

解决方案


有多种方法可以做到这一点。一种可能性是在合并之前使用第一个数组中的 id 过滤第二个数组。

获取 ID:

$ids = array_flip(array_column($first, 'id'));

创建过滤器:

$distinct = function($item) use ($ids) { return !isset($ids[$item['id']]); };

过滤和合并:

$result = array_merge($first, array_filter($second, $distinct));

推荐阅读