PHP的问题:如何array_intersect_assoc()递归 [英] PHP Question: how to array_intersect_assoc() recursively
问题描述
比方说,我想这样做:
$a = array_intersect_assoc(
array(
'key1' => array(
'key2' => 'value2'
),
'key3' => 'value3',
'key4' => 'value4'
),
array(
'key1' => array(
'key2' => 'some value not in the first parameter'
),
'key3' => 'another value'
)
);
var_dump( $a );
打印的结果是:
array
'key1' =>
array
'key2' => string 'value2' (length=6)
很显然,与KEY2在两个数组关联的值是不一样的,但 array_intersect_assoc()
还是回到键2'=> '值'
作为相交的值。
It's clear that values associated with 'key2' in both arrays are not the same, however array_intersect_assoc()
still return 'key2' => 'value2'
as the intersected value.
这是的预期的行为array_intersect_assoc()
?
谢谢!
推荐答案
是的,这是预期的行为,因为比较字符串使用重新presentations完成,并且该功能不下来递归嵌套的数组。从手动:
Yes, it's the expected behavior, because the comparison is done using string representations, and the function does not recurse down nested arrays. From the manual:
在键=>值,这两个值的对被认为是平等的前提的(字符串)$ elem1 ===(字符串)$ elem2时的。换句话说严格类型检查被执行,以便该字符串重新presentation必须相同。
The two values from the key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict type check is executed so the string representation must be the same.
如果你试图用'键1'=&GT数组相交; 数组
,你会得到相同的结果,因为数组的字符串重新presentation总是数组
。
If you tried to intersect with an array with 'key1' => 'Array'
, you'd get the same result because the string representation of an array is always 'Array'
.
一位用户注释的通过nleippe,包含一个递归实现,看起来很有希望(我修改了第三行做任何非数组值字符串比较):
One of the user-contributed notes, by nleippe, contains a recursive implementation that looks promising (I modified the third line to do string comparison on any non-array values):
function array_intersect_assoc_recursive(&$arr1, &$arr2) {
if (!is_array($arr1) || !is_array($arr2)) {
// return $arr1 == $arr2; // Original line
return (string) $arr1 == (string) $arr2;
}
$commonkeys = array_intersect(array_keys($arr1), array_keys($arr2));
$ret = array();
foreach ($commonkeys as $key) {
$ret[$key] =& array_intersect_assoc_recursive($arr1[$key], $arr2[$key]);
}
return $ret;
}
这篇关于PHP的问题:如何array_intersect_assoc()递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!