-1

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"]
]```
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Tech
  • 35
  • 6
  • Ok, so have you tried looping? Where are you stuck? – nice_dev Oct 24 '22 at 03:09
  • How might your input data vary? Are all of the 2nd level keys static? Are the keys always known and the same? Will the subarray always have only one element? – mickmackusa Oct 24 '22 at 03:48
  • We should probably help you to amend the script that is generating this unwanted data structure. I could post `array_map(fn($v) => ['key' => $v['key'][0]], $array)` but that is an extremely inflexible and literal solution for this problem. This isn't going to be much help to future researchers with similar problems. Why wouldn't you just want the simplest form: `['items1', 'items2']` (since you know that all keys will be `key`) ? – mickmackusa Oct 24 '22 at 03:55
  • [["username" => "erick","location" => ["singapore"],"province" => ["jatim"]],["username" => "thomas","location" => ["ukraina"],"province" => ["anonymouse"]]] – Tech Oct 24 '22 at 04:17
  • Please aways post question details in the question body, not as comments. – mickmackusa Oct 24 '22 at 04:41

2 Answers2

0

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:

$data = [
  ["username" => "erick","location" => ["singapore"],"province" => ["jatim"]],
  ["username" => "thomas","location" => ["ukraina"],"province" => ["anonymouse"]]
];

$result = array_map(function ($arr) {
  return array_map(function($inner) { 
    return is_array($inner) ? $inner[0] : $inner; 
  }, $arr);
}, $data);

Output (for the sample data):

array (
  0 => 
  array (
    'username' => 'erick',
    'location' => 'singapore',
    'province' => 'jatim',
  ),
  1 => 
  array (
    'username' => 'thomas',
    'location' => 'ukraina',
    'province' => 'anonymouse',
  ),
)

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
0

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)

var_export(
    array_map(
        fn($arr) =>
            array_map(
                fn($v) => ((array) $v)[0],
                $arr
            ),
        $data
    )
);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136