phparraysmultidimensional-arrayarray-unique

PHP remove duplicate array values


Let me explain my situation, i got myself a multidimensional array.. Down below is the print_r of my array.

    Array
(
    [0] => Array
        (
            [firstname] => Tinga
            [lastname] => 
            [email] => private@information.nl
            [country_code] => NL
            [group] => B2B
            [order_count] => 321
        )

    [1] => Array
        (
            [firstname] => Tinga
            [lastname] => 
            [email] => private@information.nl
            [country_code] => NL
            [group] => B2B
            [order_count] => 12
        )

    [2] => Array
        (
            [firstname] => Rijsbergen Automotive B.V.
            [lastname] => 
            [email] => private@information1.nl
            [country_code] => NL
            [group] => B2B
            [order_count] => 311
        )

    [3] => Array
        (
            [firstname] => Mike Verhoef
            [lastname] => Artis Garage Amsterdam
            [email] => private@information2.nl
            [country_code] => NL
            [group] => B2B
            [order_count] => 260
        )

    [4] => Array
        (
            [firstname] => Marc Kraak
            [lastname] => Vakgarage TEMA
            [email] => private@information3.nl
            [country_code] => NL
            [group] => B2B
            [order_count] => 257
        )

    [5] => Array
        (
            [firstname] => J&B Auto's
            [lastname] => 
            [email] => private@information4.nl
            [country_code] => NL
            [group] => B2B
            [order_count] => 249
        )
)

As you can see, there is a duplicate array, only the order_count is different.

I can easily remove the duplicates using array_unique, but then it removes one of the arrays randomly(i believe).

What i want is to remove the duplicates based on email (private_information) with the least amount of order_count. (So only keep the one with the highest order_count)

Anyone who can help me out here?


Solution

  • Solution based on provided array is:

    $filtered = [];
    foreach ($array as $item) {
        $email = $item['email'];
    
        if (empty($filtered[$email]) || $filtered[$email]['order_count'] < $item['order_count']) {
            $filtered[$email] = $item;
        }
    }