PHP删除重复的数组值

时间:2019-12-12 14:41:56

标签: php arrays multidimensional-array array-unique

让我解释一下我的情况, 我得到了一个多维数组。 下面是我的数组的print_r

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

如您所见,这里有一个重复的数组,只有order_count是不同的。

我可以轻松地使用array_unique删除重复项,但随后它会随机删除其中一个数组。(我相信)。

我想要的是基于电子邮件(private_information)以最少的order_count删除重复项。 (因此,只保留order_count最高的那个)

有人可以在这里帮助我吗?

1 个答案:

答案 0 :(得分:2)

基于提供的数组的解决方案是:

$filtered = [];
foreach ($array as $item) {
    $email = $item['email'];

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