How in php to replace the key in an array, with the key of a sub-array to get this effect:
from:
`Array
(
[0] => Array
(
[for_a] => me
)
[1] => Array
(
[for_b] => you
)
[2] => Array
(
[for_c] => bleeh
)
)`
to:
`Array
(
[for_a] => me
[for_b] => you
[for_c] => bleeh
)`
I tried with array_column, but it had no effect
3
Answers
You could do it like this:
This method assumes that there is only one element in each (the hardcoded
[0]
s in$arr2[array_keys($arr)[0]] = array_values($arr)[0];
)It is not the most elegant way. There is a method called array_walk where you can define a callback function parsing each element of your array, in which you can make sure you don’t overwrite the existing elements of the array.
@Josste gave a good example, and here’s another way you could do it:
Looping through your array twice, once to grab the parent array and then again for each of the children then use the parent key to update a
new
array key for the output.Try this php script: