I need to flatten a 2d array to become a 1d array without losing my numeric 2nd level keys in the process.
Sample data:
[
[2015 => '2015'],
[2016 => '2016'],
[2017 => '2017'],
[2018 => '2018'],
[2019 => '2019'],
[2020 => '2020'],
[2021 => '2021'],
[2022 => '2022'],
[2023 => '2023']
]
Desired output:
[
2015 => '2015',
2016 => '2016',
2017 => '2017',
2018 => '2018',
2019 => '2019',
2020 => '2020',
2021 => '2021',
2022 => '2022',
2023 => '2023'
]
Is it possible to get output like this?
3
Answers
RESULTS
You could do simple foreach loop:
Output:
I originally closed this page with this canonical page: How to Flatten a Multidimensional Array? After consulting with a moderator, it was advised that this question with narrower requirements should be reopened instead of clarifying the behavior of each answer on the other page which contains a mixture of viable and non-viable solutions for this question.
Here is a rather comprehensive list of viable techniques:
array_reduce()
using the union operator with PHP7.4’s arrow function syntax generates no variables in the global scope. (Demo)array_reduce()
usingarray_replace()
with PHP7.4’s arrow function syntax generates no variables in the global scope. (Demo)Converting the data from recursive iterator methods to an array generates no variables in the global scope. Demo
array_walk()
requires a global variable to be declared and it is modified by reference in the closure and callskey()
. Demoarray_walk_recursive()
requires a global variable to be declared and it is modified by reference in the closure without callingkey()
. DemoNested
foreach()
loops generate multiple variables in the global scope, but call no functions. DemoThere are other viable approaches that use manually scripted recursion and generators but they are less attractive in terms of readability and are likely to be overkill for this task (in my opinion).
Now for the approaches that must not be used because they lose the numeric associative keys in the rows. DON’T use these flattening techniques for this question’s data set / requirements.
var_export(array_merge(...$array));
var_export(call_user_func_array('array_merge', $array));
var_export(array_reduce($array, 'array_merge', []));
Laravel’s
Arr::flatten()
method implements manually written recursive code which returns a flat, indexed array — not appropriate for this case.Ouzo goodies’s
Array::flatten()
method usesarray_walk_recursive()
to return an flat, indexed array — not appropriate for this case.