0

How to remove duplicate values from a multidimensional array.

For example, I have an array:

Array
(
    [0] => Array
        (
            [fruit_id] => cea2fc4b4058
            [title] => Apple title one
            [name] => Apple
            [weight] => 22
        )

    [1] => Array
        (
            [fruit_id] => sdfsdec4b4058
            [title] => Grapefruit title one
            [name] => Grapefruit 
            [weight] => 19
        )

    [2] => Array
        (
            [fruit_id] => hjkvcbc4b4058
            [title] => Grapefruit title two
            [name] => Grapefruit
            [weight] => 17
        )

    [3] => Array
        (
            [fruit_id] => tyuutcgbfg058
            [title] => Lemon title one
            [name] => Lemon
            [weight] => 15
        )

    [4] => Array
        (
            [fruit_id] => lkjyurtws4058
            [title] => Mango title
            [name] => Mango
            [weight] => 13
        )

    [5] => Array
        (
            [fruit_id] => bner3223df058
            [title] => Lemon title two
            [name] => Lemon
            [weight] => 11
        )
)

In this array, I need to leave only one fruit with the maximum weight. I want to save all the data, but at the same time remove duplicate fruits. Thank.

Sergey Kozlov
  • 452
  • 5
  • 17
  • Possible duplicate of [How to remove duplicate values from a multi-dimensional array in PHP](https://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php) – clearshot66 Jan 30 '19 at 19:54
  • I tried this method it did not change the result. – Sergey Kozlov Jan 30 '19 at 19:59

2 Answers2

1

You can sort by weight ascending and then create a result using the name as the key so the ones with larger weight will overwrite the smaller weight ones:

array_multisort(array_column($array, 'weight'), SORT_ASC, $array);
foreach($array as $v) { $result[$v['name']] = $v; }

Then if you want to re-index (not required):

$result = array_values($result);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
-1

Try to use array_unique($array); code