3

I often have a 2-dimensional array:

array(
  array('key' => 'value1'),
  array('key' => 'value2'),
  ...
);

And need to form a 1-dimensional array:

array('value1', 'value2')

This can easily be done with foreach, but I wonder if there's some php 5.3 way to do it in one line.

j0k
  • 22,600
  • 28
  • 79
  • 90
Dziamid
  • 11,225
  • 12
  • 69
  • 104
  • http://stackoverflow.com/questions/1319903/how-to-flatten-a-multidimensional-array – Haim Evgi Aug 04 '11 at 11:06
  • http://stackoverflow.com/questions/2473844/how-to-get-array-of-values-from-an-associative-arrays – Haim Evgi Aug 04 '11 at 11:07
  • I wouldn't know of any build-in function which *returns a column* from such an array structure. All you could achieve is hiding the needed loop (using closures). – Yoshi Aug 04 '11 at 11:07
  • From performance point of view, I would stick with either `foreach`. – binaryLV Aug 04 '11 at 11:14

4 Answers4

6
$new_array = array_map(function($el) { return $el['key']; }, $array);
Dogbert
  • 212,659
  • 41
  • 396
  • 397
1
<?php
    $arr = array(array(141,151,161,140),2,3,array(101,202,array(303,404),407));
    function array_oned($arrays){
        static $temp_array = array();
        foreach($arrays as $key){
            if(is_array($key)){
                array_oned($key);
            }else {
                $temp_array [] = $key;
            }
        }
        return $temp_array;
    }
    echo print_r(array_oned($arr));

?>

Did you mean something like this ?

Dexy86
  • 72
  • 1
  • 5
0
array_reduce($array,function($arr,$new){
    $arr[]=$new['key'];
},array())
RiaD
  • 46,822
  • 11
  • 79
  • 123
0

In case, when you have only one value in inner arrays:

$values = array_map('array_pop', $yourArray);

Callback could be function name, so why reimplement something that already exists as a core function? :)

Radek Benkel
  • 8,278
  • 3
  • 32
  • 41