1

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.

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

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

3
  • how you come to know that ['key'=>'foo', 'Rating'=>5] , is a duplicate and need to remove. look at your desired output and tell Commented Jan 4, 2017 at 18:56
  • 1
    you should also post the part where you fetch the data from MySQL and also post table structure with data because your question is marked as MySQL.... the best solution would be the let the database handle the grouping and max values something like this... SELECT Rates.key , MAX(Rates.Rating) FROM Rates GROUP BY Rates.key Commented Jan 4, 2017 at 19:08
  • Possible duplicate of Creating Multidimensional Nested Array from MySQL Result with Duplicate Values (PHP) Commented Jan 4, 2017 at 21:17

1 Answer 1

1

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

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.