php - 在删除重复项时合并两个多维数组,依赖于它们的特定元素
问题描述
我正在研究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 2
和1st array index 1
)。我几乎尝试了所有方法来弄清楚如何删除合并中的第一个或第二个,但PHP
每次都用错误和警告回复我。
我的目标是将两个数组合二为一,根据“名称”元素删除重复项。
我感谢任何可以帮助我的人,我被困住了。
解决方案
有多种方法可以做到这一点。一种可能性是在合并之前使用第一个数组中的 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));
推荐阅读
- javascript - 在 reducer 中更新搜索功能的状态
- rest - ORDS 18.4 为什么我得到一个空的 :body_text (CLOB)?
- java - 将 Firebase 应用与 Google 登录一起使用时,如何使用我的 Google Cloud Function 进行身份验证?
- debugging - 在 Vis.Code 中设置调试配置以附加到 gdbserver 时出现问题
- html - 为什么内联块之间会出现垂直和水平间隙?
- javascript - 在 Javascript 中的 img 中显示来自 Java Servlet 的 BinaryStream
- python - Python Google Analytics 活跃用户列表
- excel - 解压后下载压缩的 csv 文件
- mysql - Sequelize 迁移失败并显示 errno:150“外键约束格式不正确”
- flutter - 如何使用 SharedPreferences 保存和检索自定义对象列表?