php - 我在 php 中有多维数组,想要在 3 列的基础上删除重复的条目

标签 php mysql arrays multidimensional-array

我有这样的数组,如果这 3 列匹配,我想根据 sender_idreceiver_idclassifieds_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/

相关文章:

php - 使用 Laravel 5.2 集合中的列名获取唯一值的计数

mysql - 当文件添加到目录时,如何让 Windows 批处理或 Perl 脚本运行?

php android spinner - JSONObject 无法转换为 JSONArray

javascript - 使用push和shift方法反转数组

javascript - 根据时区 (GMT + 8) 设置 javascript Fullcalendar 插件

php - 显示子域根目录下域文件夹的内容

PHP - 连接到多个 MySQL 数据库

javascript - javascript数组中条目的成对组合

python - 如何使用numpy掩码计算二维数组

php - 数组排序算法