Php 如何确定二维数组中是否存在重复项
我有这样一个数组:Php 如何确定二维数组中是否存在重复项,php,arrays,multidimensional-array,Php,Arrays,Multidimensional Array,我有这样一个数组: Array( ["dest0"] => Array( ["id"] => 1, ["name"] => name1 ), ["dest1"] => Array( ["id"] => 2, ["name"] => name2
Array(
["dest0"] => Array(
["id"] => 1,
["name"] => name1
),
["dest1"] => Array(
["id"] => 2,
["name"] => name2
),
["dest2"] => Array(
["id"] => 3,
["name"] => name3
),
["dest3"] => Array(
["id"] => 1,
["name"] => name1
)
);
要检查其中是否有重复的值(比如这里的dest0和dest3是重复的),我不想删除它们,只要检查是否有
谢谢。您可以使用以下代码找出重复项(如果有):
仅基于检查重复id,而不是同时检查id和名称,但易于修改:
$duplicates = array();
array_walk($data, function($testValue, $testKey) use($data, &$duplicates){
foreach($data as $key => $value) {
if (($value['id'] === $testValue['id']) && ($key !== $testKey))
return $duplicates[$testKey] = $testValue;
}
} );
if (count($duplicates) > 0) {
echo 'You have the following duplicates:',PHP_EOL;
var_dump($duplicates);
}
你的意思是你需要一种更有效的方法?是只有两个维度还是可以有任意维度?@Gumbo就像例子中那样只有两个维度。只检查重复的
id
值就足够了吗?谢谢你的回复,是的,就够了
$duplicates = array();
array_walk($data, function($testValue, $testKey) use($data, &$duplicates){
foreach($data as $key => $value) {
if (($value['id'] === $testValue['id']) && ($key !== $testKey))
return $duplicates[$testKey] = $testValue;
}
} );
if (count($duplicates) > 0) {
echo 'You have the following duplicates:',PHP_EOL;
var_dump($duplicates);
}