How to get second level values from multidimensional array?
Without looping.
Usually developers would go for foreach
to loop over every value and add them to previously created empty array.
This will result in desired output, but I will show how this can be done with one line and no looping.
Let's consider following input data:
$data = [
[
1,
2,
3
],
[
4,
5
]
];
Desired result (resulting var_dump
):
array(5) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
}
Solution: use call_user_func_array
with array_merge
.
$result = call_user_func_array('array_merge', $data);
And we have all values in one array.
What if arrays have matching keys? permalink
Idea with matching keys is to only get second level arrays values (without keys).
Let's consider following input data:
$data = [
[
'key' => 1,
2,
3
],
[
'key' => 4,
5
]
];
Now previous solution would give as (resulting var_dump
):
// Bad
// Missing value of 1 and we have key "key"
array(4) {
["key"]=>
int(4)
[0]=>
int(2)
[1]=>
int(3)
[2]=>
int(5)
}
To fix it, array_map
and array_values
will help us out.
// >= PHP7.4
$result = call_user_func_array('array_merge', array_map(fn($arr) => array_values($arr), $data));
// < PHP7.4
$result = call_user_func_array('array_merge', array_map(function($arr){return array_values($arr);}, $data));
And we still have one liner and result again is as expected:
array(5) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
}
This post is based on my answer on Stack Overflow. If this helped you, consider upvoting it.