0

I want to search an array for duplicate values in each subarray and if there is one, only keep the highest value connected to this item.

That's my question, but I love to add an example to clarify things!

This is my array:

Array
(
    [0] => Array
        (
            [groupid] => 1
            [points]  => 5
        )
    [1] => Array
        (
            [groupid] => 1
            [points]  => 1
        )
    [2] => Array
        (
            [groupid] => 1
            [points]  => 4
        )
    [3] => Array
        (
            [groupid] => 2
            [points]  => 1
        )
)

As you can see, the first three items have the same groupid. I want to match those items and see which of them has the highest points. The other one (with the lowest points) should be kicked out of the array.

So in this case, item 0, 1 and 2 are from the same group, but 2 has the highest points. 0 and 1 should be dropped out of the array.

My desired result would be something like this:

Array
(
    [0] => Array
        (
            [groupid] => 1
            [points]  => 5
        )
    [1] => Array
        (
            [groupid] => 2
            [points]  => 1
        )
)

I've been trying for a few hours now but no luck yet. Maybe I am overlooking something very simple and thinking to hard to figure this out... Any help would be appreciated!

EDIT It's a Drupal site (but that shouldn't make any difference) and this is query:

foreach ($promotions as $value) {
   $promo = db_query("SELECT * FROM {_promo_articles} WHERE art = :art AND promoid = :promoid", array(
        ':art'      => $value['product'][0]->sku,
        ':promoid'  => $value['promo_id'][0])) ->fetchAll();
}
4

4 回答 4

4

正如我从您的评论中看到的那样,信息来自数据库,因此请执行以下操作:

(伪代码)

SELECT group_id, MAX(points) 
FROM db_table
GROUP BY group_id;
于 2013-07-15T13:41:38.443 回答
0

我会做类似的事情:

$final_array = array();
foreach($array AS $element)
{
    if(!isset($final_array[$element["groupid"]]) ||
       $final_array[$element["groupid"]] < $element["points"])
            $final_array[$element["groupid"]] = $element["points"];
}

然后,$final_array看起来像...

Array
(
    [1] => 5
    [2] => 1
)

(第 1 组得 5 分,第 2 组得 1 分)

于 2013-07-15T13:43:00.780 回答
0

您可以使用usort函数按顺序排列数组points。此函数将从大到小对其进行排序:

usort($myArray, function($a, $b) {
    return $b['points'] - $a['points'];
});
于 2013-07-15T13:50:17.793 回答
0

如评论中所述,如果可以选择,最好的方法是从您的数据库中获取。

如果没有,您可以使用 array_reduce 和闭包(PHP 5.3+)

 $array = array_reduce($array,function(&$result, $val){ 
                         if (!array_key_exists($val["groupid"], $result){
                           $result[$val["groupid"]] = $val;    
                         } else {
                           if ($result[$val["groupid"]]["points"] < $val["points"])
                               $result[$val["groupid"]]["points"] = $val["points"];  
                         }
                       }, array());

然后,如果您想重置密钥

$array = array_values($array);
于 2013-07-15T13:50:41.207 回答