I am attempting to build a function that allows searching of multi-dimensional arrays where each sub-array matches multiple conditions. I'm encountering a weird behaviour and can't figure out why it is happening.
The following is the general logic that causes the issue. I'm running this on PHP 7.4 for what it's worth. The final array of keys ($keys2) is expected to match the first array of keys ($keys), but instead it loses its association with the expected indexes. It appears that PHP is ignoring my given int indexes and using un-seen 0-indexed indexes on the final array_keys() call instead.
$array = [
['one' => 'aa', 'two' => 'qq'],
['one' => 'bb', 'two' => 'qq'],
['one' => 'aa', 'two' => 'qq'],
['one' => 'bb', 'two' => 'qq'],
['one' => 'aa', 'two' => 'qq'],
];
$keys = array_keys(array_column($array, 'one'), 'aa');
$array2 = array_filter($array, static function($key) use ($keys) {
return in_array($key, $keys, true);
}, ARRAY_FILTER_USE_KEY);
$keys2 = array_keys(array_column($array2, 'two'), 'qq');
echo '<pre>';
var_dump($array, $keys, $array2, $keys2);
echo '</pre>';
The above outputs:
/var/www/test.php:
array (size=5)
0 =>
array (size=2)
'one' => string 'aa' (length=2)
'two' => string 'qq' (length=2)
1 =>
array (size=2)
'one' => string 'bb' (length=2)
'two' => string 'qq' (length=2)
2 =>
array (size=2)
'one' => string 'aa' (length=2)
'two' => string 'qq' (length=2)
3 =>
array (size=2)
'one' => string 'bb' (length=2)
'two' => string 'qq' (length=2)
4 =>
array (size=2)
'one' => string 'aa' (length=2)
'two' => string 'qq' (length=2)
/var/www/test.php:
array (size=3)
0 => int 0
1 => int 2
2 => int 4
/var/www/test.php:27:
array (size=3)
0 =>
array (size=2)
'one' => string 'aa' (length=2)
'two' => string 'qq' (length=2)
2 =>
array (size=2)
'one' => string 'aa' (length=2)
'two' => string 'qq' (length=2)
4 =>
array (size=2)
'one' => string 'aa' (length=2)
'two' => string 'qq' (length=2)
/var/www/test.php:
array (size=3)
0 => int 0
1 => int 1
2 => int 2
array_columnjust returns the values from the column you specify; it doesn't look at the keys. Hence you get a result which is indexed as0, 1, 2.... You might find this easier to implement via a simpleforeachloop.array_column($array2, 'two'). You don't need to be a slave to the PHParray_x()functions, in instances like this it will look cleaner to write your own function. If you're looking for a quick solution, just usearray_combine()witharray_keys($array2)to apply the old keys to the new array.