Search code examples
phpmultidimensional-arrayfilteringarray-intersectarray-key

Filter 2D associative array using keys from multiple levels of another 2D associative array


I have two 2-dimensional arrays and want to filter the first array's data using the second array so that the only elements retained are where the keys in the first and second levels match.

$array1 = [
    'a1' => ['a_name' => 'aaaaa', 'a_value' => 'aaa'],
    'b1' => ['b_name' => 'bbbbb', 'b_value' => 'bbb'],
    'c1' => ['c_name' => 'ccccc', 'c_value' => 'ccc'],
];

$array2 = [
    'b1' => ['b_name' => 'does not matter'],
];

In other words, I want the intersection of keys of $array1 and $array2. The result must be from $array1.

Desired result:

['b1' => ['b_name' => 'bbbbb']]

Solution

  • function recursive_array_intersect_key(array $array1, array $array2) {
        $array1 = array_intersect_key($array1, $array2);
        foreach ($array1 as $key => &$value) {
            if (is_array($value) && is_array($array2[$key])) {
                $value = recursive_array_intersect_key($value, $array2[$key]);
            }
        }
        return $array1;
    }
    

    Demo here.