Multidimensional array to array
Asked Answered
U

4

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.

Unanimity answered 4/8, 2011 at 11:0 Comment(4)
#1320403Scenography
#2474344Scenography
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).Mucronate
From performance point of view, I would stick with either foreach.Claustral
C
6
$new_array = array_map(function($el) { return $el['key']; }, $array);
Courtier answered 4/8, 2011 at 11:3 Comment(0)
A
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 ?

Ane answered 30/10, 2012 at 16:32 Comment(0)
S
0
array_reduce($array,function($arr,$new){
    $arr[]=$new['key'];
},array())
Samarium answered 4/8, 2011 at 11:5 Comment(0)
A
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? :)

Amiamiable answered 4/8, 2011 at 11:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.