I want to merge all sub arrays of an array in an older project that requires >=5.3.3.
The array mentioned above looks like this:
$array = Array (
Array
(
[0] => 26
[1] => 644
)
Array
(
[0] => 20
[1] => 26
[2] => 644
)
Array
(
[0] => 26
)
Array
(
[0] => 47
)
Array
(
[0] => 47
[1] => 3
[2] => 18
)
Array
(
[0] => 26
[1] => 18
)
Array
(
[0] => 26
[1] => 644
[2] => 24
[3] => 198
[4] => 8
[5] => 6
[6] => 41
[7] => 31
)
Array
(
[0] => 26
[1] => 644
[2] => 24
[3] => 198
[4] => 12
[5] => 25
[6] => 41
[7] => 31
)
Array
(
[0] => 198
)
Array
(
[0] => 198
)
Array
(
[0] => 899
))
Now, I’m wondering how I could merge all of those Subrrays into one that looks like this:
Array
(
[1] => 26
[2] => 644
[3] => 20
[4] => 26
[5] => 644
[6] => 26
[7] => 47
[8] => 47
[9] => 3
[10] => 18
[11] => 26
[12] => 18
[13] => 26
[14] => 644
[15] => 24
[16] => 198
[17] => 8
[18] => 6
[19] => 41
[20] => 31
[21] => 26
[22] => 644
[23] => 24
[24] => 198
[25] => 12
[26] => 25
[27] => 41
[28] => 31
[29] => 198
[30] => 198
[31] => 899
)
I know how this could work on a more up to date PHP version. So far on this older version I’ve tried the following:
print_r(array_merge($array, $emptyArray));
But I get the exact same Array returned.
I also tried something like this:
$result_arr = array();
foreach ($array as $sub_arr) $result_arr = array_merge($result_arr, $sub_arr);
$result_arr = array_unique($result_arr);
print_r($result_arr);
Which tells me my second argument is not an array?
I’m a bit confused and hope someone can shed some light on this issue.
3
Answers
this function, I think, will do it well.
All you have to do is send your array as a parameter of the function, and display the result.
Working since PHP 4
You could use
array_walk_recursive()
, which will visit each leaf node of the input array, then add this value to an output array…Your foreach approach is fine, and works for me. But I don’t see why you are filtering with array_unique.
Output:
To flatten with the splat (Php 5.6):
For pre-splat versions:
Or array_reduce:
If in doubt foreach:
All the above result in the same zero indexed array.