tags:

views:

80

answers:

4

From:

$arr = array(array('key1'=>'A',...),array('key1'=>'B',...));

to:

array('A','B',..);
A: 

Relatively simple conversion by looping:

$newArray = array()
foreach ($arr as $a) {
    foreach ($a as $key => $value) {
        $newArray[] = $value;
    }
}

Or, perhaps more elegantly:

function flatten($concatenation, $subArray) {
    return array_merge($concatenation, array_values($subArray));
}
$newArray = array_reduce($arr, "flatten", array());

John's solution is also nice.

Tom Bartel
Is there a built-in function to do this kind of job?
Mask
I believe there is no built-in function to do exactly this.
Tom Bartel
@Mask, Not with associative arrays. Otherwise you could create a new array use one of several functions or the "+" operator to create a Union of the arrays.
Thomas
Your mention of array_map is good!
Mask
Thanks, but my `array_map()` solution was wrong (only included the first element of each sub-array). Try the new one using `array_reduce()`.
Tom Bartel
Now that I read John's comment, only the first element of each sub-array might actually be what you want... Well, choose one version ;-)
Tom Bartel
+1  A: 
$output = array();
foreach ($arr as $array_piece) {
  $output = array_merge($output, $array_piece);
}
return array_values($output);

On the other hand, if you want the first value from each array, what you want is...

$output = array();
foreach ($arr as $array_piece) {
  $output[] = array_unshift($array_piece);
}

But I'm thinking you want the first one.

John Fiala
A: 

Something like this should work

<?
$arr = array(array('key1'=>'A','key2'=>'B'),array('key1'=>'C','key2'=>'D'));

$new_array = array();

foreach ($arr as $key => $value) {
    $new_array = array_merge($new_array, array_values($value));
}

var_export($new_array);
?>

If you want all the values in each array inside your main array.

houmam
A: 
function collapse($input) {
    $buf = array();
    if(is_array($input)) {
     foreach($input as $i) $buf = array_merge($buf, collapse($i));
    }
    else $buf[] = $input;
    return $buf;
}

Above is a modified unsplat function, which could also be used:

function unsplat($input, $delim="\t") {
    $buf = array();
    if(is_array($input)) {
     foreach($input as $i) $buf[] = unsplat($i, $delim);
    }
    else $buf[] = $input;
    return implode($delim, $buf);
}
$newarray = explode("\0", unsplat($oldarray, "\0"));
Rob