比较相同数组值

3

在PHP中,比较同一数组中的元素的最佳方式是什么,以便如果数组A中有两个具有相同值的元素,则可以将函数作为参数传递以执行某些操作?


你能举个例子说明数组的样子吗?如果发现重复项,你希望函数做什么? - PeeHaa
4个回答

5
您可以使用array_count_valuesin_array函数,如下所示:
if(in_array(2,array_count_values($array)) {
  // do something
}

2
如果您想查找数组中所有重复的值,可以像这样操作:
// Array to search:
$array = array('one', 'two', 'three', 'one');
// Array to search:
// $array = array('a'=>'one', 'b'=>'two', 'c'=>'three', 'd'=>'one');
// Temp array so we don't find the same key multipule times:
$temp = array();
// Iterate through the array:
foreach ($array as $key)
{
    // Check the key hasn't already been found:
    if (!in_array($key, $temp))
    {
        // Get an array of all the positions of the key:
        $keys = array_keys($array, $key);
        // Check if there is more than one position:
        if (count($keys)>1)
        {
            // Add the key to the temp array so its not found again:
            $temp[] = $key;
            // Do something...
            echo 'Found: "'.$key.'" '.count($keys).' times at position: ';
            for($a=0;$a<count($keys);$a++)
            {
                echo $keys[$a].','; 
            }                   
        }
    }
}

以上的输出结果如下:

上述代码的输出为:

在位置 0 和 3 找到了 "one",共出现了 2 次。

如果你的数组使用了自定义键名 (如注释中的数组),则输出结果为:

在位置 a 和 d 找到了 "one",共出现了 2 次。


将for循环改为foreach循环,以防数组具有自定义键而不是默认的数字键。 - Scoobler

1

我猜你想要合并两个数组并去除重复项。

$array1 = array('a', 'b', 'c');
$array2 = array(1, 2, 3, 'a');

// array_merge() merges the arrays and array_unique() remove duplicates
var_dump(array_unique(array_merge($array1, $array2)));

// output: array('a', 'b', 'c', 1, 2, 3)

1

使用array_udiff或类似函数(如果您想要能够修改值,请在回调中使用引用参数):

$array1 = array('foo', 'bar', 'baz');
$array2 = array('foo', 'baz');

$result = array_udiff($array1, $array2, function(&$a, &$b) {
     if ($a == $b) {
         $a = $b = 'same!';
         return 0;
     }
     return $a > $b ? 1 : -1;
});

print_r($array1); // array('same!', 'bar', 'same!')
print_r($array2); // array('same!', 'same!')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接