I have an array which is multidimensional for no reason
/* This is how my array is currently */
Array
(
[0] => Array
(
[0] => Array
(
[plan] => basic
)
[1] => Array
(
[plan] => small
)
[2] => Array
(
[plan] => novice
)
[3] => Array
(
[plan] => professional
)
[4] => Array
(
[plan] => master
)
[5] => Array
(
[plan] => promo
)
[6] => Array
(
[plan] => newplan
)
)
)
I want to convert this array into this form
/*Now, I want to simply it down to this*/
Array (
[0] => basic
[1] => small
[2] => novice
[3] => professional
[4] => master
[5] => promo
[6] => newplan
)
Any idea how to do this?
You can do it just using a loop.
Recently I've been using AlienWebguy's array_flatten function but it gave me a problem that was very hard to find the cause of.
array_merge causes problems, and this isn't the first time that I've made problems with it either.
If you have the same array keys in one inner array that you do in another, then the later values will overwrite the previous ones in the merged array.
Here's a different version of array_flatten without using array_merge:
Your sample array has 3 levels. Because the first level has only
[0]
, you can hardcode your access into it and avoid an extra function/construct call.(Code Demos)
array_walk_recursive() is handy and versatile, but for this task may be overkill and certainly a bit more convoluted in terms of readability.
If this was my code, I'd be using array_column() because it is direct and speaks literally about the action being performed.
Of course a couple of `foreach() loops will perform very efficiently because language constructs generally perform more efficiently than function calls.
Finally, as a funky alternative (which I can't imagine actually putting to use unless I was writing code for someone whom I didn't care for) I'll offer an array_merge_recursive() call with a splat operator (
...
).Following this pattern
Call the function :
Function Declaration :
}
Assuming this array may or may not be redundantly nested and you're unsure of how deep it goes, this should flatten it for you:
Just assign it to it's own first element: