新数组中php数组的相同值

时间:2012-12-29 18:52:24

标签: php arrays

我有阵列问题,没有我的朋友:)

我有一个这个数组:

Array
(
    [0] => 2012163115
    [1] => 2012163115
    [2] => 2012161817
    [3] => 201214321971
    [4] => 201214321971
    [5] => 201214321971
)

我需要这个,所有变量出现不止一次

Array
(
    [0] => 2012163115
    [1] => 201214321971
)

我试试这个

foreach ($array as $val) {
                    if (!in_array($val, $array_temp)) {
                        $array_temp[] = $val;
                    } else {
                        array_push($duplis, $val);
                    }
                }

但结果是

Array
(
    [0] => 2012163115
    [1] => 201214321971
    [2] => 201214321971
)

我的错误在哪里?谢谢你的帮助!

4 个答案:

答案 0 :(得分:3)

array_unique()适合你。

编辑:操作我没有注意到“不止一次”的条款,在这种情况下:

$yourArray = array('a', 'a', 'b', 'c');

$occurrences = array();

array_walk($yourArray, function($item) use(&$occurrences){

    $occurrences[$item]++;

});


$filtered = array();

foreach($occurrences as $key => $value){

    $value > 1 && $filtered[] = $key;

}

var_dump($filtered);

答案 1 :(得分:2)

$array = array(
  '2012163115',
  '2012163115',
  '2012161817',
  '201214321971',
  '201214321971',
  '201214321971',
);

$duplication = array_count_values($array);
$duplicates = array();
array_walk($duplication, function($key, $value) use (&$duplicates){
  if ($key > 1)
    $duplicates[] = $value;
});
var_dump($duplicates);

答案 2 :(得分:0)

请参阅http://php.net/manual/en/function.array-unique.php#81513

这些是添加的字符,以使SO接受帖子!

答案 3 :(得分:0)

$array_counting = array();
foreach ($array as $val)
    if ( ! in_array($val, $array_counting))
    {
        $array_counting[$val] ++; // counting  
    }

$array_dups = array();
foreach ($array_counting as $key => $count)
{
    if ($count > 1)
        $array_dups[] = $key; // this is more than once
}