Mask
Mask

Reputation: 34207

How to get values in an array this way with PHP?

From:

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

to:

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

Upvotes: 0

Views: 179

Answers (4)

Rob
Rob

Reputation: 8195

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

Upvotes: 0

Tom Bartel
Tom Bartel

Reputation: 2258

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.

Upvotes: 0

John Fiala
John Fiala

Reputation: 4581

$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.

Upvotes: 1

houmam
houmam

Reputation: 464

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.

Upvotes: 0

Related Questions