我有2个数组:

$array1 = ["b" => "no", "c" => "no", "d" => ["y" => "no"]];
$array2 = ["a" => "yes", "b" => "yes", "c" => "yes", "d" => ["x" => "yes", "y" => "yes", "z" => "yes"]];


我想返回$array2的成员,这些成员的键也出现在$array1中。

所需的输出:

$array3 = ["b" => "yes", "c" => "yes", "d" => ["y" => "yes"]];


基本上,我需要与array_intersect_key相同的功能,但我想保留$array2而不是$array1的值。

是否存在这样的功能?还需要递归到子数组中。谢谢!

*编辑*
正如安德里(Andri)在his comment中所建议的那样,我试图翻转array_intersect_key($array2, $array1)周围的参数,但在这种情况下,我真正得到的是:

$array3 = ["b" => "yes", "c" => "yes", "d" => ["x" => "yes", "y" => "yes", "z" => "yes"]];


即“ d”的所有子元素,只是因为在$array1中提到了“ d”。

最佳答案

据我所知,没有内置函数,使用递归处理所有层的方法应该很容易...

$array1 = ["b" => "no", "c" => "no", "d" => ["y" => "no"]];
$array2 = ["a" => "yes", "b" => "yes", "c" => "yes", "d" => ["x" => "yes", "y" => "yes", "z" => "yes"]];

function intersect_key_2 ( array $a1, array $a2 )   {
    foreach ( $a1 as $key1 => $value1)  {
        // If there is a matching element
        if ( isset($a2[$key1]) )    {
            // Update - if an array, use recursive call else just replace
            $a1[$key1] = ( is_array($value1) ) ? intersect_key_2 ( $value1, $a2[$key1])
                    : $a2[$key1];
        }
    }

    return $a1;
}

print_r(intersect_key_2($array1, $array2));




Array
(
    [b] => yes
    [c] => yes
    [d] => Array
        (
            [y] => yes
        )

)

关于php - PHP array_intersect_key但保留array2的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59107175/

10-13 02:01