在多维数组中查找重复项并回显它们

Find duplicates in a multidimensional array and echo out them

我想在多维数组中找到重复项,然后回显出哪些有重复项,哪些没有。我试过这段代码。

    $teams = array
  (
  "grupp_A" => array('Arsenal','Arsenal','Barcelona'),
  "grupp_B" => array('Milan','Man United','Barcelona'),
  "grupp_C" => array('Juventus','Barcelona','Barcelona'),
  "grupp_D" => array('Arsenal','Man United','Barcelona')
  );



foreach ( $teams as $key => $val ) {

  foreach($val as $k => $v) {

    if(count(array_unique($k))<count($k))
{
    echo "Array: $v has duplicates<br>";
}
else
{

    echo "Array: $v does not have duplicates<br>";
    }
    }
    }

然后我得到结果

Array: Arsenal has duplicates
Array: Arsenal has duplicates
Array: Barcelona has duplicates
Array: Milan has duplicates
Array: Man United has duplicates
Array: Barcelona has duplicates
Array: Juventus has duplicates
Array: Barcelona has duplicates
Array: Barcelona has duplicates
Array: Arsenal has duplicates
Array: Man United has duplicates
Array: Barcelona has duplicates

但结果应该是这样的。

Array: grupp_A has duplicates
Array: grupp_C has duplicates
Array: grupp_B does not have duplicates
Array: grupp_D does not have duplicates

我被卡住了,不知道自己做错了什么,需要一些帮助。

我按照建议用 in_array 尝试了这段代码。

foreach ( $teams as $key => $val ) {

    if (in_array($key, $val)) {

    echo "Array: $key has duplicates<br>";
}
else
{

    echo "Array: $key does not have duplicates<br>";
    }
    }

给出了输出

Array: grupp_A does not have duplicates
Array: grupp_B does not have duplicates
Array: grupp_C does not have duplicates
Array: grupp_D does not have duplicates

有点近了,但还没到。

我喜欢你的 array_unique 方法,很抱歉我对 in_array 的评论打扰了你。

foreach ($teams as $key => $val) {
    if (count(array_unique($val)) == count($val)) {
        echo $key . " has no duplicates" . PHP_EOL;
    } else {
        echo $key . " has duplicates" . PHP_EOL;
    }
}

只需一个循环就够了,因为你把俱乐部聚集在一起:

foreach($teams as $group => $clubs)
{
    if( count(array_unique($clubs)) < count($clubs) )
        echo "Group $group has duplicates" . PHP_EOL ;
    else
        echo "Group $group has no duplicates" . PHP_EOL ;
}

输出:

Group grupp_A has duplicates

Group grupp_B has no duplicates

Group grupp_C has duplicates

Group grupp_D has no duplicates