我有这样的数组,如果这 3 列匹配,我想根据 sender_id
、receiver_id
和 classifieds_id
来唯一它2 数组,然后我想根据创建的列删除旧的数组,如果任何 2 列匹配,则不会发生任何情况,只有匹配的 3 列数组才会被删除
Array (
[0] => Array ( [0] => 131826 [user_id] => 131826 [1] => 131826 [sender_id] => 131826 [2] => 141332 [receiver_id] => 141332 [3] => 1055971 [classifieds_id] => 1055971 [4] => 1 [status] => 1 [5] => 2016-04-07 12:37:42 [created] => 2016-04-07 12:37:42 )
[1] => Array ( [0] => 141332 [user_id] => 141332 [1] => 141332 [sender_id] => 141332 [2] => 131826 [receiver_id] => 131826 [3] => 1055971 [classifieds_id] => 1055971 [4] => 1 [status] => 1 [5] => 2016-04-07 12:30:06 [created] => 2016-04-07 12:30:06 )
[2] => Array ( [0] => 141332 [user_id] => 141332 [1] => 141332 [sender_id] => 141332 [2] => 131826 [receiver_id] => 131826 [3] => 1055971 [classifieds_id] => 1055971 [4] => 1 [status] => 1 [5] => 2016-04-07 12:28:32 [created] => 2016-04-07 12:28:32 )
[3] => Array ( [0] => 131826 [user_id] => 131826 [1] => 131826 [sender_id] => 131826 [2] => 141332 [receiver_id] => 141332 [3] => 1055971 [classifieds_id] => 1055971 [4] => 1 [status] => 1 [5] => 2016-04-06 12:28:53 [created] => 2016-04-06 12:28:53 )
)
最佳答案
这是构建复合键以删除重复项的快速方法。但首先按日期降序排序,以便最旧的排在前面,并将在循环中被覆盖。如果它是一个 SQL 查询并且您可以在查询中对其进行排序,则不需要排序:
array_multisort(array_column($array, 'created'), SORT_DESC, $array);
foreach($array as $v) {
$result[$v['sender_id'].'-'.$v['receiver_id'].'-'.$v['classifieds_id']] = $v;
}
// if you want to re-index
$result = array_values($result);
实际上,如果这是一个数据库查询,可能有一种方法SELECT DISTINCT
,但 SQL 专家需要回答这个问题。
关于php - 我在 php 中有多维数组,想要在 3 列的基础上删除重复的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36480183/