如何检查多维数组是否包含相同的值? [英] How to check if multidimensional array contains same value?
本文介绍了如何检查多维数组是否包含相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个多维数组.我需要检查此数组中的任何值是否包含相同的值.如果执行,则执行.什么是更好的检查方法,还是最简单的TIA方法
I have a multidimensional array. I need to check if any value in this array has contain same value. If, then execute. What is the better way to check this, or the simplest way 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
)
)
推荐答案
如果我正确理解了您的问题,则您正在寻找一种方法来查找出现在多个内部数组中的值.这是使用一些内置的PHP数组方法的两种解决方案.
If I understood your question correctly, you are looking for a way of finding values that appears in more than one of the inner arrays..? Here are two solutions for that, using some built-in PHP array methods.
设置
- 使用代码:
$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中获取一个唯一值的数组
(已删除重复项) - 通过比较该数组以获取删除的内容(=重复项)原始的
$ array
- 确保值在最终数组中仅出现
- Get an array of unique values in
$array
(duplicates removed) - Get what was removed (= the duplicates) by comparing that array to the original
$array
- Make sure values appear only once in the final array
代码:
$duplicates = array_unique( array_diff_key( $array, array_unique($array) ) ); // $duplicates = 5, 2, 6, 10
方法B
- 获取每个值出现多少次的列表在
$ array
中 - 过滤器,该列表仅保留出现多次的值(=重复)
- 获取该列表的键(实际的
$ array
值)
- Get a list of how many times each value appears in
$array
- Filter that list keeping only values that appears more than once (= duplicates)
- Get the keys of that list (the actual
$array
values)
代码:
$duplicates = array_keys( array_filter( array_count_values($array), function ($count) { return $count > 1; } ) ); // $duplicates = 5, 10, 2, 6
这篇关于如何检查多维数组是否包含相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 在
查看全文