-1

I have an array that needs to be redone (preferably a built-in function of PHP):

[
   0 => ['ax' => 'Aland Islands'],
   1 => ['as' => 'American Samoa'],
   2 => ['am' => 'Armenia']
];

Need to remake on:

[
    'ax' => 'Aland Islands'
    'as' => 'American Samoa'
    'am' => 'Armenia'
];
Mohammad
  • 21,175
  • 15
  • 55
  • 84
Bin
  • 21

2 Answers2

0

You can select inner array and use array_merge() to create new array with target structure.

$arr = [
    0 => ['ax' => 'Aland Islands'],
    1 => ['as' => 'American Samoa'],
    2 => ['am' => 'Armenia']
];
$newArr = array_merge($arr[0], $arr[1], $arr[2]);

If the array contain many inner array, use

$newArr = array_merge(...$arr);

Also you can iterate array and insert inner array into new variable.

foreach ($arr as $item){
    $key = array_keys($item)[0];
    @$newArr[$key] = $item[$key];
}

Check result in demo

Mohammad
  • 21,175
  • 15
  • 55
  • 84
0

Use array_reduce():

$array = [
    0 => ['ax' => 'Aland Islands'],
    1 => ['as' => 'American Samoa'],
    2 => ['am' => 'Armenia']
 ];

print_r(
    array_reduce($array, 
                    function ($c, $i) {
                        return array_merge($c, $i);
                    },
                    []
                )
       );

Outputs:

Array
(
 [ax] => Aland Islands
 [as] => American Samoa
 [am] => Armenia
)

A very useful function, goes well beyond of sum/product accumulation !

Agnius Vasiliauskas
  • 10,935
  • 5
  • 50
  • 70