1

What would be a good way to transform an array that looks like:

Array (
    [0] = Array (
            [0] = Array (
                    [key] = val
                    [key2] = val2
                )

        )
    [1] = Array (
            [0] = Array (
                    [key] = val
                    [key2] = val2
                )

        )
)

to

Array (
    [0] = Array (
            [key] = val
            [key] = val2
        )
    [1] = Array (
            [key] = val
            [key] = val2
        )
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
mike23
  • 11
  • 1

5 Answers5

5

This might be a rather neat way of doing it

$output=array_map('array_shift', $input);

This uses array_map to call array_shift on each each element of the input array, which will give you the first element of each sub-array! Nice little one-liner, no?

Nice as it is, it's not terribly efficient as array_shift does more work than we need - a simple loop is actually far faster (I just did a quick benchmark on an array with 1000 elements and this was around 6x faster)

$output=array();
foreach ($input as $element){
    $output[]=$element[0];
}
Paul Dixon
  • 295,876
  • 54
  • 310
  • 348
  • Funnily enough I was doing that too, expecting it to be faster - it was about the same as array_shift though. – Paul Dixon May 31 '11 at 22:11
1
$new=array();
foreach($array as $a){
  $new[]=array_shift($a);
}
Trey
  • 5,480
  • 4
  • 23
  • 30
0

I think everyone over thought this one. This is exactly what array_column() does.

Code: (Demo)

$array=[
    [
        ['key'=>'val','key2'=>'val2']
    ],
    [
        ['key'=>'val','key2'=>'val2']
    ]
];
var_export(array_column($array,0));

Output:

array (
  0 => 
  array (
    'key' => 'val',
    'key2' => 'val2',
  ),
  1 => 
  array (
    'key' => 'val',
    'key2' => 'val2',
  ),
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
0
$new=array();
foreach ($array as $a){
$new[]=$a[0];
}

print_r($new);
0

If your array is $my_array and has 2 elements, you can:

$my_array = array_merge($my_array[0], $my_array[1]);

Hope that helped.

Tadeck
  • 132,510
  • 28
  • 152
  • 198