0

Having a bit of a brainfart here, I've got an array that looks like this:

Array ( 
[0] => Array ( 'fruit' => 'orange', ) 
[1] => Array ( 'fruit' => 'apple', )
)

annnnnnnnd it's got to end up like this:

Array ( 
[0] => 'orange'
[1] => 'apple' 
)

How do I do this?

onoe
  • 1

2 Answers2

3

You can use array_map and array_shift

$array = array_map('array_shift', $array);

or just loop over it:

foreach($array as $key=>$value) {
    $array[$key] = array_shift($value);
}

Update: Using array_shift is much better if you always want to get the first value or if the subarrays contain only one value anyway...

If you have a more complicated structure, e.g. more elements in the subarrays, then you basically want to flatten your array.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • @onoe: And my solution did not work? `reset` and `array_shift` are doing the same thing in a way. `array_shift` is more self-explanatory than `reset`. – Felix Kling Dec 20 '10 at 23:32
0

If the key isn't always the same (i.e. if it isn't always fruit), you could do this:

<?php
$source = array( 
    0 => array ( 'fruit' => 'orange', ) 
    1 => array ( 'fruit' => 'apple', )
);     

$destination = array();

foreach($source as $source_array)
{
    foreach($source_array as $value)
    {
        $destination[] = $value;
    }
}
?>
White Elephant
  • 1,361
  • 2
  • 13
  • 28