根据特定键从多维数组中删除重复的值 [英] Remove duplicate values from a multidimensional array based on a specific key

查看:92
本文介绍了根据特定键从多维数组中删除重复的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个这样的多维数组:

Got a multidimensional array like this one:

[['key'=>'foo', 'Rating'=>5] ,  
 ['key'=>'bar', 'Rating'=>1] ,
 ['key'=>'Tee', 'Rating'=>3] ,
 ['key'=>'foo', 'Rating'=>10] ,
 ['key'=>'foo', 'Rating'=>1]]

我想基于特定键和评级系统删除重复项,同时保留原始数组

I want to remove duplicates based on a specific key and a Rating system while maintaining the original array structure except index keys.

所以最终结果应如下所示:

So the final result should look like this:

[['key'=>'bar', 'Rating'=>1] ,
 ['key'=>'Tee', 'Rating'=>3] ,
 ['key'=>'foo', 'Rating'=>10]] 

我正在寻找解决这个问题的有效方法。

I'm looking for an efficient solution to this problem.

理想情况下,一个 array_unique()函数接受一个键值作为参数,以查找给定数组上的重复项和 Rating 键。

Ideally an array_unique() function that accepts a key value as a parameter to find repetitions on a given array and the Rating key.

array_key_unique($array, $uniqe_key, $Rating);

我想知道是否可以通过MySQL查询做到这一点?

I was wondering if there is any way to do this with MySQL query?

推荐答案

Raymond Nijland 所述注释,最好在查询中执行:

As Raymond Nijland states in the comments, better to do it in the query:

SELECT `key`, MAX(`Rating`) FROM `table_name` GROUP BY `key`

但是由于我很无聊,所以循环并添加<$ c最高的那个$ c>对结果进行评分:

But because I was bored, loop and add the one with highest Rating to the result:

foreach($array as $value) {
    if(!isset($result[$value['key']]) || $result[$value['key']]['Rating'] < $value['Rating']) {
        $result[$value['key']] = $value;
    }
}

或者,对ASCending排序并提取 key 作为覆盖重复项的索引:

Or, sort ASCending and extract an array with key as the index to overwrite duplicates:

array_multisort(array_column($array, 'key'),
                array_column($array, 'Rating'),
                SORT_ASC, $array);

$result = array_column($array, null, 'key');

无论哪种情况,要重新索引到基于整数的数组,请使用:

In either case, to re-index to an integer based array, use:

$result = array_values($result);

这篇关于根据特定键从多维数组中删除重复的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆