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.

4
  • stackoverflow.com/questions/1319903/… Commented Aug 4, 2011 at 11:06
  • stackoverflow.com/questions/2473844/… Commented Aug 4, 2011 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). Commented Aug 4, 2011 at 11:07
  • From performance point of view, I would stick with either foreach. Commented Aug 4, 2011 at 11:14

4 Answers 4

6
$new_array = array_map(function($el) { return $el['key']; }, $array);
Sign up to request clarification or add additional context in comments.

Comments

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 ?

Comments

0
array_reduce($array,function($arr,$new){
    $arr[]=$new['key'];
},array())

Comments

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? :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.