在php二维数组中查找重复项
我在php中有一个二维数组,如下所示:在php二维数组中查找重复项,php,filter,duplicates,Php,Filter,Duplicates,我在php中有一个二维数组,如下所示: Array ( [0] => Array ( [index1] => -1 [index2] => 77 [description] => 7 ) [1] => Array
Array (
[0] => Array
(
[index1] => -1
[index2] => 77
[description] => 7
)
[1] => Array
(
[index1] => -1
[index2] => 77
[description] => 5
)
[2] => Array
(
[index1] => -1
[index2] => 78
[description] => 12
)
)
我需要找出第一级数组之间是否存在重复。
但仅考虑index1和index2键
在上面的示例中,它应该返回true,因为0和1具有相同的index1和index2。有两种方法可以帮助您:
1.如果您只想删除重复项,可以使用:
2.如果要查找DUP,可以扫描阵列,并“针对每个”项目-使用以下命令检查阵列的其余部分:
这不是一个非常有效的算法,但是假设外部数组是数字索引的暴力方式:
function hasDuplicates($array) {
$count = count($array);
for ($i = 0; $i < $count; $i++){
for ($j = $i+1; $j < $count; j++) { // check every later element in the array
if ($array[i]['index1'] == $array[j]['index1'] && $array[i]['index2'] == $array[j]['index2']) {
return true;
}
}
}
return false;
}
函数有重复($array){
$count=计数($array);
对于($i=0;$i<$count;$i++){
对于($j=$i+1;$j<$count;j++){//检查数组中以后的每个元素
if($array[i]['index1']==$array[j]['index1']&&$array[i]['index2']]==$array[j]['index2'])){
返回true;
}
}
}
返回false;
}
<?php
$a=array(
array('index1'=>-1,'index2'=>77,'description'=>7),
array('index1'=>-1,'index2'=>77,'description'=>5),
array('index1'=>-1,'index2'=>78,'description'=>12)
);
function check($a){
$data=array();
foreach($a as $arr){
if ($data[$arr['index1'].'|'.$arr['index2']]) {
return true;
}
$data[$arr['index1'].'|'.$arr['index2']]=true;
}
return false;
}
if (check($a)) {
echo "duplicates found";
}else{
echo "no duplicates";
}
?>
您应该使用分隔符,否则数组(index1=>-1,index2=>77)和数组(index1=>-17,index2=>7)将不起作用,例如。@stewe-thx,已添加。但实际上分隔符不能是第一个或最后一个字符,否则数组(index1=>'-1 |',index2=>77)和数组(index1=>'-1',index2=>'-77')将无法工作。无论如何
<?php
$a=array(
array('index1'=>-1,'index2'=>77,'description'=>7),
array('index1'=>-1,'index2'=>77,'description'=>5),
array('index1'=>-1,'index2'=>78,'description'=>12)
);
function check($a){
$data=array();
foreach($a as $arr){
if ($data[$arr['index1'].'|'.$arr['index2']]) {
return true;
}
$data[$arr['index1'].'|'.$arr['index2']]=true;
}
return false;
}
if (check($a)) {
echo "duplicates found";
}else{
echo "no duplicates";
}
?>