如何通过将数组索引与另一个数组索引进行比较来删除数组索引?
PHP:
$results = array ( array(
"Name" => $NameUser,
"Surname" => $SurnameUser,
"MyComment" => $MyComment,
"VideoPath" => $VideoPath,
"Reg_Date" => $Reg_Date,
"ThumbPath" => $ThumbPath,
"UserId" => $UserId
));
print_r($results[0]); // Array ( [Name] => aaa [Surname] => aaa [MyComment] => aaa [VideoPath] => aaa [Reg_Date] => aaa [ThumbPath] => aaa [UserId] => aaa)
$JSON_List = file_get_contents('test.json');
$arr = json_decode($JSON_List);
print_r($arr[0]); // stdClass Object ( [Name] => aaa [Surname] => aaa [MyComment] => aaa [VideoPath] => aaa [Reg_Date] => aaa [ThumbPath] => aaa [UserId] => aaa )
我可以看到这两个索引是相同的,我正在使用for循环,但它寻求php没有看到它们是相同的。
如何正确比较数组,如果相同,则从列表中删除相同的数组索引?
PHP:
foreach ($arr as $index) {
$countIndex++;
print_r($countIndex);
if ($arr[$countIndex - 1] == $results[0]) {
print_r("array is identical \n");
}else{
print_r("array is not identical \n");
}
}
答案 0 :(得分:2)
检查两个独立数组中是否存在两个键的简单方法是使用array_intersect_key()
函数。
$sameKeys = array_intersect_key($arr1, $arr2);
答案 1 :(得分:0)
您可以使用:array_unique( array_merge($arr1, $arr2) );
或者这个:
$arr_1 = array_diff($arr1, $arr2);
$arr_2 = array_diff($arr2, $arr1);
答案 2 :(得分:0)
有2个阵列:
$results = array ( array(
"Name" => '$NameUser',
"Surname" => '$SurnameUser',
"MyComment" => '$MyComment',
"VideoPath" => '$VideoPath',
"Reg_Date" => '$Reg_Date',
"ThumbPath" => '$ThumbPath',
"UserId" => '$UserId'
)
);
// print_r($results[0]);
//$JSON_List = file_get_contents('test.json');
//$arr = json_decode($JSON_List);
$arr = array(array(//simulate
"Name" => '$NameUser',
"Surname" => '$SurnameUser',
"MyComment" => '$MyComment',
"VideoPath" => '$VideoPath',
"Reg_Date" => '$Reg_Date',
"ThumbPath" => '$ThumbPath',
"UserId" => '$UserId'
),
array(
"Name" => '$NameUser2',
"Surname" => '$SurnameUser2',
"MyComment" => '$MyComment2',
"VideoPath" => '$VideoPath2',
"Reg_Date" => '$Reg_Date2',
"ThumbPath" => '$ThumbPath',
"UserId" => '$UserId2'
));
//Search identicals
function search_identicals(&$arr,$results){
$response = array();
foreach($results as $k=>$value){
array_walk($arr,function($elem,$key)use($value,&$response,&$arr){
$resp = array_diff($elem,$value);
if(empty($resp)){
unset($arr[$key]);
array_push($response,$elem);
}
});
}
return ($response) ? $response : false;
}
$identicals = search_identicals($arr,$results);
var_dump('to delete');
var_dump($identicals);
var_dump('deleted');
var_dump($arr);
//你只需要这个:
function search_identicals(&$arr,$results){//&$arr by reference
foreach($results as $k=>$value){
array_walk($arr,function($elem,$key)use($value,&$arr){
$resp = array_diff($elem,$value);//if is identical, return empty
if(empty($resp)){
unset($arr[$key]);//remove repeated
}
});
}
}