我怎样才能得到所有数组元素,其中的值只有数组中出现一次? [英] How can I get all array elements, where the value only occurs once in the array?

查看:164
本文介绍了我怎样才能得到所有数组元素,其中的值只有数组中出现一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让所有的数组元素,其中的值只有数组中出现一次。

I'm trying to get all array elements, where the value only occurs once in the array.

我试图用

array_unique($array);

但这只是删除重复的,这不是我想要的。

But this does only remove the duplicates, which is not what I want.

作为一个例子:

$array =  0 => 1
          1 => 2
          2 => 3
          3 => 4
          4 => 5
          5 => 2
          6 => 3
          7 => 4
          8 => 5

期望的输出:

array(
   0=>1
 )

正如你所看到的仅值1数组中出现一次,所有其他的值比数组中的一次。所以,我只想说一个元素保留。

As you can see only the value 1 occurs once in the array, all other values are more than once in the array. So I only want to keep that one element.

推荐答案

这应该为你工作:

第一次使用 array_count_values​​() 计算每个值有多少次是你的数组中为止。这将返回是这样的:

First use array_count_values() to count how many times each value is in your array. This will return something like this:

Array (
    [1] => 1
    [2] => 2
    [3] => 2
    [4] => 2
    [5] => 2
//   ↑     ↑
// Value Amount
)

之后,你可以使用 array_filter() 只能获得价值,你的阵列中出现一次。意思是:

After that you can use array_filter() to only get the values, which occurs once in your array. Means:

Array (
    [1] => 1
    [2] => 2
    [3] => 2
    [4] => 2
    [5] => 2
)

和结尾只需使用 array_keys() 从原来的数组中获得的价值。

And at the end simply use array_keys() to get the value from the original array.

code:

<?php

    $arr = [1,2,3,4,5,2,3,4,5];
    $result = array_keys(array_filter(array_count_values($arr), function($v){
        return $v == 1;
    }));

    print_r($result);

?>

输出:

Array (
    [0] => 1
)

这篇关于我怎样才能得到所有数组元素,其中的值只有数组中出现一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆