php - 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']]
Answer
Solution:
Demo here.
Answer
Solution:
Answer
Solution:
Demo of 2 dimensional associative array intersection in PHP
The Code:
How to run it:
Unit tests to prove that the above code works as designed:
The above code prints:
All dots means everything passed.
What cases does this code take care of?
What it doesn't do:
It doesn't test for nulls/undefined/dissimilar depth arrays, nor arrays 2 or more layers deep. If datatypes get swapped, comparing strings to ints, or floats to octals, it will probably fail. It's difficult to get PHP to do equality correctly. http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/
Do everything you can to try to do this work in the database, doing it in PHP blows the horn to summon the fail whale. It's inefficient, so you better not be operating on more than a few hundred items. It's going to surprise left jab you on unexpected cases, and it's kind of hard to read/understand what it's doing under the hood.
Answer
Solution:
Because you are filtering arrays of consistent depth, recursion is not explicitly required.
array_intersect_key()
.Code: (Demo)
Output:
Answer
Solution:
I think you should check if the $array2[$key] is an array, too.