我有一个多维数组。我需要检查此数组中的任何值是否包含相同的值。如果,然后执行。检查这个的最好方法是什么,或者最简单的方式TIA
$array[] = array(5, 10, 15, 20, 25, 30);
$array[] = array(1, 2, 3, 4, 5, 6);
$array[] = array(2, 6, 8, 10, 12, 14);
Array
(
[0] => Array
(
[0] => 5
[1] => 10
[2] => 15
[3] => 20
[4] => 25
[5] => 30
)
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
[2] => Array
(
[0] => 2
[1] => 6
[2] => 8
[3] => 10
[4] => 12
[5] => 14
)
)
答案 0 :(得分:1)
只需循环遍历数组和子阵列,使用值和外观频率填充$ isRepeated。当$ isRepeated [Certain_value]存在时,意味着在以下位置找到此值:
$array[] = array(5, 10, 15, 20, 25, 30);
$array[] = array(1, 2, 3, 4, 5, 6);
$array[] = array(2, 6, 8, 10, 12, 14);
$isRepeated = array();
foreach($array as $subArray) {
foreach($subArray as $item) {
if (!isset($isRepeated[$item])) {
$isRepeated[$item] = 0;
} else {
$isRepeated[$item]++;
echo "\n<br>Item $item is repeated";
}
}
}
输出:
Item 5 is repeated
Item 2 is repeated
Item 6 is repeated
Item 10 is repeated
答案 1 :(得分:1)
如果我正确理解了您的问题,那么您正在寻找一种方法来查找出现在多个内部数组中的值。?以下是两种解决方案,使用一些内置的PHP数组方法。
<强>设置强>
$array
(两种方法的初始步骤)代码:
$array[] = array(5, 10, 15, 20, 25, 30);
$array[] = array(1, 2, 3, 4, 5, 6);
$array[] = array(2, 6, 8, 10, 12, 14, 5);
// 5, 10, 15, 20, 25, 30, 1, 2, 3, 4, 5, 6, 2, 6, 8, 10, 12, 14, 5
$array = call_user_func_array('array_merge', $array);
方法A
$array
中删除unique values的数组(已移除重复项)$array
代码:
$duplicates =
array_unique(
array_diff_key(
$array,
array_unique($array)
)
);
// $duplicates = 5, 2, 6, 10
方法B
$array
$array
值)代码:
$duplicates =
array_keys(
array_filter(
array_count_values($array),
function ($count) {
return $count > 1;
}
)
);
// $duplicates = 5, 10, 2, 6