skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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
        )
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search