mike23
mike23

Reputation: 11

Partially-flattening a multi-dimensional array

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
        )
)

Upvotes: 1

Views: 141

Answers (5)

mickmackusa
mickmackusa

Reputation: 47764

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',
  ),
)

Upvotes: 0

Paul Dixon
Paul Dixon

Reputation: 300805

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];
}

Upvotes: 5

user557846
user557846

Reputation:

$new=array();
foreach ($array as $a){
$new[]=$a[0];
}

print_r($new);

Upvotes: 0

Trey
Trey

Reputation: 5520

$new=array();
foreach($array as $a){
  $new[]=array_shift($a);
}

Upvotes: 1

Tadeck
Tadeck

Reputation: 137290

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.

Upvotes: 0

Related Questions