Php 比较两个多维数组
Php:比较Php中的2个多维数组 我有02个阵列,我想比较一下。Php 比较两个多维数组,php,arrays,Php,Arrays,Php:比较Php中的2个多维数组 我有02个阵列,我想比较一下。 $first = array( 0 => array( "id" => 45, "name" => "chicago" ), 1 => array( "id" => 78, "name"
$first = array(
0 => array(
"id" => 45,
"name" => "chicago"
),
1 => array(
"id" => 78,
"name" => "LA"
),
);
$second = array(
0 => array(
"id" => 45,
"name" => "chicago"
),
1 => array(
"id" => 78,
"name" => "LA"
),
2 => array(
"id" => 95,
"name" => "Washington"
),
);
比较两个阵列后,我希望
$cityMissing =array (
0 => array(
"id" => 95,
"name" => "Washington"
);
**Please, I need your help.**
您可以使用:
请告诉我们您首先尝试了什么,以便我们可以帮助您修复它。这将是一个注释。它不起作用,我有一个错误:注意:数组到字符串的转换
$arrayFirst = array("0" => array("id", "45") );
$arraySecond = array("0" => array("id", "45"), "1" => array("id", "95"));
$result = array_diff_assoc($arraySecond, $arrayFirst);
print_r($result);
Array
(
[1] => Array
(
[0] => id
[1] => 95
)
)
public static function array_diff_assoc_recursive($a, $b){
// Get all of the "compare against" arrays
$b = array_slice(func_get_args(), 1);
// Initial return value
$ret = array();
// Loop over the "to" array and compare with the others
foreach($a as $key=>$val){
// We should compare type first
$aType = gettype($val);
// If it's an array, we recurse, otherwise we just compare with "==="
$args = $aType === 'array' ? array($val) : true;
// Let's see what we have to compare to
foreach($b as $x){
// If the key doesn't exist or the type is different,
// then it's different, and our work here is done
if(!array_key_exists($key, $x) || $aType !== gettype($x[$key])){
$ret[$key] = $val;
continue 2;
}
// If we are working with arrays, then we recurse
if($aType === 'array'){
$args[] = $x[$key];
}
// Otherwise we just compare
else{
$args = $args && $val === $x[$key];
}
}
// This is where we call ourselves with all of the arrays we got passed
if($aType === 'array'){
$comp = call_user_func_array(array(get_called_class(), 'array_diff_assoc_recursive'), $args);
// An empty array means we are equal :-)
if(count($comp) > 0){
$ret[$key] = $comp;
}
}
// If the values don't match, then we found a difference
elseif(!$args){
$ret[$key] = $val;
}
}
return $ret;
}