如何检查多维数组是否有重复值

how to check multidimensional array for duplicated value

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

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

if there there then return true else return 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] => 
        )



)

如果你有 PHP 5.5+ 可用,函数 array_column() 可以很容易地提取子数组的第一个 "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() 来仅 return 来自 $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')