且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据特定键从多维数组中删除重复的值

更新时间:2023-02-23 09:12:19

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`

但是由于我很无聊,所以循环并添加对结果进行评分:

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);