如何检查多维数组的重复值

时间:2015-01-08 14:52:06

标签: php arrays for-loop

我有这个数组,我不想删除重复的值.. 我想检查第一个值是否有重复

  

([0] => 1500,[0] => 1111,[0] => 1500)

如果有则返回true,否则返回false如何执行此操作?

Array
(
    [0] => Array
        (
            [0] => 1500
            [1] => first
            [2] => 
            [3] => 
            [4] => 50
            [5] => 
            [6] => 
        )

    [1] => Array
        (
            [0] => 1111
            [1] => second
            [2] => 
            [3] => 
            [4] => 10
            [5] => 
            [6] => 
        )

    [2] => Array
        (
            [0] => 1500
            [1] => third
            [2] => 
            [3] => 
            [4] => 100
            [5] => 
            [6] => 
        )



)

1 个答案:

答案 0 :(得分:1)

如果你有PHP 5.5+可用,函数array_column()可以很容易地提取第一个"列"子数组,并将结果数组提供给array_count_values(),这将产生一个像[1500] => 2, [1111] => 1这样的值数组,您可以从中轻松推导出哪些> 1

这看起来像是:

// PHP 5.5+ only...
// Gets counts of each first sub-array value
$counts = array_count_values(array_column($input_multidimensional_array, 0));
// Test that the array key has > 1

// To check a specific one for duplicates:
if (isset($counts['1500']) && $counts['1500'] > 1) {
   // Yes, it has duplicates.
}

但是...... 由于你没有PHP 5.5+,你必须使用某种形式的循环。

$temp = array();
foreach ($input_multidimensional_array as $sub_array) {
  // A temporary array holds all the first elements
  $temp[] = $sub_array[0];
}
// Count them up
$counts = array_count_values($temp);

// Then use the same process to check for multiples/duplicates:
if (isset($counts['1500']) && $counts['1500'] > 1) {
   // Yes, it has duplicates.
}

在其中任何一种情况下,您也可以使用array_filter()仅从具有倍数的$counts返回数组。

// Filter to only those with > 1 into $only_duplicates
$only_duplicates = array_filter($counts, function($v) {
  return $v > 1;
});
// To further reduce this only to the _values_ themselves like 1500, 1111
// use array_keys:
$only_duplicates = array_keys($only_duplicates);
// is now array('1500')