This is my input:
[
["username" => "erick", "location" => ["singapore"], "province" => ["jatim"]],
["username" => "thomas", "location" => ["ukraina"], "province" => ["anonymouse"]]
]
How can I flatten the inner arrays to string values?
Expected output:
[
["username" => "erick", "location" => "singapore", "province" => "jatim"],
["username" => "thomas", "location" => "ukraina", "province" => "anonymouse"]
]```
2
Answers
You could use a nested
array_map
to convert your data, checking for inner values that are arrays and if they are, returning the first value in the array, otherwise just returning the value:Output (for the sample data):
Demo on 3v4l.org
Since your subarray values are either scalar or a single-element array, you can unconditionally cast the value as an array then access the first element.
Using nested
array_map()
calls will get you down to the elements on that second level of the structure.Code: (Demo)