phparraysmultidimensional-array

Get a single column of values from a 2d array


If from a function I am returned a multidimensional array like this..

array(
    0 => array('a' => 5),
    1 => array('a' => 8)
)

But I just really need the contents of the key 'a' what is the best way for me to convert.

Current I have been doing something like...

$new_array = array();

foreach ($multi_array AS $row) {
    $new_array[] = $row['a']
}

Solution

  • If that is all your requirements are, I think that is the best way. Anything else will have the same processing. Even after looking through the Array functions, I would say that this would be the best way. You can, however, make it a function to make it a bit more versatile:

    $array = array(0 => array('a' => 1), 1 => array('a' => 8));
    
    $new_array = flatten($array, 'a');    
    
    function flatten($array, $index='a') {
         $return = array();
    
         if (is_array($array)) {
            foreach ($array as $row) {
                 $return[] = $row[$index];
            }
         }
    
         return $return;
    }
    

    But yea, I would say what you have would be the most efficient way of doing it.