PHP从多维数组中删除重复的值

时间:2019-01-30 19:50:42

标签: php

如何从多维数组中删除重复值。

例如,我有一个数组:

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

在这个数组中,我只需要留一个重量最大的水果。 我想保存所有数据,但同时删除重复的水果。 谢谢。

2 个答案:

答案 0 :(得分:1)

您可以按weight升序排序,然后使用name作为键来创建结果,因此,weight较大的将覆盖较小的weight:< / p>

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

然后,如果您想重新编制索引(不需要):

$result = array_values($result);

答案 1 :(得分:-1)

尝试使用array_unique($array);代码