如何从PHP中删除数组中的所有重复值?

时间:2012-10-19 20:07:57

标签: php arrays duplicates

我只想检查重复项的值[id],并删除此“字段”[id]重复的所有密钥。

示例:如果我有数字1,2,1。我希望结果是2,而不是1,2。并且重复的标准仅通过检查[id]而不是任何其他“字段”来确定。

原始数组:

Array
(
    [0] => Array
        (
            [name] => John
            [id] => 123
            [color] => red
        )

    [1] => Array
        (
            [name] => Paul
            [id] => 958
            [color] => red
        )

    [2] => Array
        (
            [name] => Jennifer
            [id] => 123
            [color] => yellow
        )
)

我想要的结果:

Array
(
    [0] => Array
        (
            [name] => Paul
            [id] => 958
            [color] => red
        )

)

4 个答案:

答案 0 :(得分:2)

我同意上面的每个人,你应该给我们更多关于你尝试过的信息,但我喜欢编码高尔夫,所以这是一个完全无法解读的解决方案:

$new_array = array_filter($array, function($item) use (&$array){
    return count(array_filter($array, function($node) use (&$item){
        return $node['id'] == $item['id'];
    })) < 2;
});

答案 1 :(得分:1)

通过几个简单的循环,这应该很容易实现:

set_time_limit(0); // Disable time limit to allow enough time to process a large dataset

// $items contains your data

$id_counts = array();
foreach ($items as $item) {
    if (array_key_exists($item['id'], $id_counts)) {
        $id_counts[$item['id']]++;
    } else {
        $id_counts[$item['id']] = 1;
    }
}

for ($i = count($items); $i >= 0; $i--) {
    if ($id_counts[$items[$i]['id']] > 1) {
        array_splice($items, $i, 1);
    }
}

结果:

Array
(
    [0] => Array
        (
            [name] => Paul
            [id] => 958
            [color] => red
        )
)

虽然有更简洁的方法可以做到这一点,但这种方法的一个优点是你只为id和重复id列表创建新数组,而array_splice正在从原始数组中删除重复数据,所以内存使用量保持在最低限度。

编辑:修正了一个错误,意味着它有时会留下一个

答案 2 :(得分:0)

function PickUniques(array $items){
    // Quick way out
    if(empty($items)) return array();
    $counters = array();
    // Count occurences
    foreach($items as $item){
        $item['id'] = intval($item['id']);
        if(!isset($counters[$item['id']])){
            $counters[$item['id']] = 0;
        }
        $counters[$item['id']]++;
    }
    // Pop multiples occurence ones
    foreach($counters as $id => $occurences){
        if($occurences > 1){
            unset($counters[$id]);
        }
    }
    // Keep only those that occur once (in $counters)
    $valids = array();
    foreach($items as $item){
        if(!isset($items[$item['id']])) continue;
        $valids[$item['id']] = $item;
    }
    return $valids;
}

试试这个:)

答案 3 :(得分:0)

这是答案的一个非常基本的方法,我相信有更好的答案,但我可能会按照我在纸面上的方式开始。

我查看第一个索引,检查其值。然后,如果值与我最初记录的值相同,我会浏览其他索引,记下它们的索引。一旦我通过列表,如果我有多个具有该特定值的索引,我将它们全部删除(从最高索引开始,以便在删除时不影响其他索引)。

对所有其他索引执行此操作,直到到达列表末尾。

它很长,但会确保删除所有重复的值。并且只留下那些最初没有重复的东西。