Make array_column () functions compatible with PHP earlier versions

Source: Internet
Author: User

Make array_column () functions compatible with PHP earlier versions

Array_column () is a very useful php Data function. It is mainly used to obtain a set of values in a column of a two-dimensional array and then form a new array, however, this function only supports php 5.5 and later versions. Therefore, we provide an implementation method for php 5.5 and later versions.

if(!function_exists('array_column')){    function array_column($arr,$key){        return array_map(function($val) use ($key){            return $val[$key];        },$arr);    }}

Or:

if(!function_exists('array_column')){    function array_column($input,$column_key,$index_key=null){        $arr=array_map(function($d) use ($column_key,$index_key){            if(!isset($d[$column_key])){                return null;            }            if($index_key!==null){                return array($d[$index_key]=>$d[$column_key]);            }            return $d[$column_key];        },$input);        if($index_key!==null){            $tmp=array();            foreach ($arr as $ar){                $tmp[key($ar)]=current($ar);            }            $arr=$tmp;        }        return $arr;    }}

Example:

<?php$records = array(    array(        'id' => 2135,        'first_name' => 'John',        'last_name' => 'Doe',    ),    array(        'id' => 3245,        'first_name' => 'Sally',        'last_name' => 'Smith',    ),    array(        'id' => 5342,        'first_name' => 'Jane',        'last_name' => 'Jones',    ),    array(        'id' => 5623,        'first_name' => 'Peter',        'last_name' => 'Doe',    )); $first_names = array_column($records, 'first_name');print_r($first_names);

The above routine will output:

Array
(
[0] => John
[1] => Sally
[2] => Jane
[3] => Peter
)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.