gpt4 book ai didi

PHP 问题 : how to array_intersect_assoc() recursively

转载 作者:可可西里 更新时间:2023-11-01 12:51:56 27 4
gpt4 key购买 nike

假设我想这样做:

$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() 仍然返回 'key2' => 'value2' 作为相交值。

这是 array_intersect_assoc() 的预期行为吗?

谢谢!

最佳答案

是的,这是预期的行为,因为比较是使用字符串表示形式完成的,并且该函数不会向下递归嵌套数组。来自manual :

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.

如果您尝试使用 'key1' => 'Array' 与数组相交,您会得到相同的结果,因为数组的字符串表示始终是 'Array'

One of the user-contributed notes ,由 nleippe 编写,包含一个看起来很有前途的递归实现(我修改了第三行以对任何非数组值进行字符串比较):

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 问题 : how to array_intersect_assoc() recursively,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4627076/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com