0

I have an array of arrays of associative arrays like this

$my_array = [
  [ 8 => "One" ],
  [ 3=>"Two" ]
]

How can I like explode all the associative arrays into one array like this

[
  8 => "One",
  3 =>"Two"
]

I tried using array_merge(...$my_array) and all it gives is

[
  0 => "One"
  1 => "Two"
]

iamafasha
  • 848
  • 10
  • 29

3 Answers3

1

This is how you can do it, by using Collection and the mapWithKeys method :

$a = [
        [
           8 => "One",
        ],
        [
           3 => "Two",
        ],
     ];

$b = collect($a)->mapWithKeys(function($a) {
   return $a;
})->toArray();

dd($b);

// [
//  8 => "One"
//  3 => "Two"
// ]
Anthony Aslangul
  • 3,589
  • 2
  • 20
  • 30
1

in plain php, and assuming those arrays will always look like that: (if you're not sure you should loop through the sub_array to get the keys)

foreach($my_array as $sub_array ){
    $new_array[key($sub_array)] = $sub_array[key($sub_array)];
}
var_export($new_array);
WdeVlam
  • 129
  • 4
1

Loop through both levels to get the keys

foreach ($my_array as $sub_array) {
    foreach ($sub_array as $key => $value) {
        $new_array[$key] = $value;
    }
}
print_r($new_array);