Built From Developers For Developers
» Kuikie.com » Snippets » PHP » Arrays » PHP. Get Column from Multidimensional Array
  Categories
  PHP
    Arrays
    Date & Time
    Files & Directories
    Globalization
    Images
    OOP
    Other
    Strings
    User Interface
 

PHP. Get Column from Multidimensional Array

The following PHP snippet gets a column from a multidimensional array. This is especially useful, if the data in the array is arranged in a table like structure.

//======================== START OF FUNCTION ==========================//
// FUNCTION: multiarray_get_column                                     //
//=====================================================================//
function multiarray_get_column($multiarray,$column_name){
    $column = array();
    foreach($multiarray as $array){
        if(isset($array[$column_name])){
            $column[] = $array[$column_name];
        }
    }
    return $column;
}
//=====================================================================//
//  FUNCTION: multiarray_get_column                                    //
//========================= END OF FUNCTION ===========================//

Example of Usage

$products = array(
    array('id'=>1,'title'=>'milk','price'=>1.80),
    array('id'=>22,'title'=>'ice cream','price'=>0.60),
    array('id'=>5,'title'=>'eggs','price'=>2.20),
);

$product_ids = multiarray_get_column($products,'id');
 
©2012 Sinevia Ltd Terms of Use         Privacy Policy Valid XHTML 1.0 Transitional