Home > Enterprise >  Convert array values on second level of 3d array to simple strings
Convert array values on second level of 3d array to simple strings

Time:10-24

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"]
]```

CodePudding user response:

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

CodePudding user response:

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
    )
);
  • Related