0

我的数组有问题,没有我的朋友 :)

我有一个这个数组:

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

4 回答 4

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);
于 2012-12-29T18:54:15.167 回答
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);
于 2012-12-29T19:04:40.850 回答
0

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

这些是为了让 SO 接受帖子而添加的字符!

于 2012-12-29T19:01:50.680 回答
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
}
于 2012-12-29T19:09:49.173 回答