我在PHP中有多维数组,并希望在3列的基础上删除重复的条目

时间:2016-04-07 15:06:20

标签: php mysql arrays multidimensional-array

我有这样的数组,我希望在sender_idreceiver_idclassifieds_id的基础上将其唯一,如果这3列在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 ) 
) 

2 个答案:

答案 0 :(得分:0)

这是一种快速构建复合键的方法,可以删除重复项。但是首先按日期降序排序,以便最老的是第一个并且将在循环中被覆盖。如果它是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大师需要回答那个。

答案 1 :(得分:0)

按照以下方式考虑您的数组。

$classifiedArr[]    = array("user_id" => "131826", "sender_id" => "131826", "receiver_id" => "141332", "classifieds_id" => "1055971", "status" => "1", "created" => "2016-04-07 12:37:42");
$classifiedArr[]    = array("user_id" => "141332", "sender_id" => "141332", "receiver_id" => "131826", "classifieds_id" => "1055971", "status" => "1", "created" => "2016-04-07 12:30:06");
$classifiedArr[]    = array("user_id" => "141332", "sender_id" => "141332", "receiver_id" => "131826", "classifieds_id" => "1055971", "status" => "1", "created" => "2016-04-07 12:28:32");
$classifiedArr[]    = array("user_id" => "131826", "sender_id" => "131826", "receiver_id" => "141332", "classifieds_id" => "1055971", "status" => "1", "created" => "2016-04-06 12:28:53");

foreach($classifiedArr as $indClassified) {
    $createUnique   = $indClassified["user_id"]."|".$indClassified["sender_id"]."|".$indClassified["receiver_id"];
    $newArray[$createUnique]    = $indClassified;
}

逻辑简单且不言自明,在这里我创建了一个新的Array,它包含user_id - sender_id - receiver_id组合的唯一数组键。