I have data stored in a PHP array like this:
(
[category1] => Array
(
[0] => Array
(
[name] => Test1
)
[1] => Array
(
[name] => Test2
)
[2] => Array
(
[name] => Test3
)
)
[category2] => Array
(
[0] => Array
(
[name] => Test4
)
)
[category3] => Array
(
[0] => Array
(
[name] => Test5
)
)
)
What functions can I use to modify this array to remove the first array keys of category1/2/3, and then reorder the numeric array keys, so the resulting array looks like this:
Array
(
[0] => Array
(
[name] => Test1
)
[1] => Array
(
[name] => Test2
)
[2] => Array
(
[name] => Test3
)
[3] => Array
(
[name] => Test4
)
[4] => Array
(
[name] => Test5
)
)
I have tried array_shift
, but this just returns 3 pieces of data, and doesn’t take into account the other categories:
[0] => Array
(
[name] => Test1
)
[1] => Array
(
[name] => Test2
)
[2] => Array
(
[name] => Test3
)
3
Answers
Try
array_merge()
function andarray_values()
like this :first loop through your array and create a new array like this
you can also use array_reduce instead of the above loop.
and then reorder your new array
The input array only contains leaf elements which are arrays with one key-value pair, and where the keys of each of these elements are identical (which means these keys are not needed in the result array).
If that really is the input this approach would work too (otherwise David Teo’s answer is the way to go):
Output: