Home >Backend Development >PHP Tutorial >兼容php二维数组取值函数array_column使用

兼容php二维数组取值函数array_column使用

WBOY
WBOYOriginal
2016-06-20 13:03:301260browse

PHP5.5发布,其中增加了一个新的数组函数array_column,感觉不错的!

但是低版本PHP要使用,得自己实现:

if(!function_exists('array_column')){ <br />    function array_column($input, $columnKey, $indexKey=null){ <br />        $columnKeyIsNumber      = (is_numeric($columnKey)) ? true : false; <br />        $indexKeyIsNull         = (is_null($indexKey)) ? true : false; <br />        $indexKeyIsNumber       = (is_numeric($indexKey)) ? true : false; <br />        $result                 = array(); <br />        foreach((array)$input as $key=>$row){ <br />            if($columnKeyIsNumber){ <br />                $tmp            = array_slice($row, $columnKey, 1); <br />                $tmp            = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null; <br />            }else{ <br />                $tmp            = isset($row[$columnKey]) ? $row[$columnKey] : null; <br />            } <br />            if(!$indexKeyIsNull){ <br />                if($indexKeyIsNumber){ <br />                    $key        = array_slice($row, $indexKey, 1); <br />                    $key        = (is_array($key) && !empty($key)) ? current($key) : null; <br />                    $key        = is_null($key) ? 0 : $key; <br />                }else{ <br />                    $key        = isset($row[$indexKey]) ? $row[$indexKey] : 0; <br />                } <br />            } <br />            $result[$key]       = $tmp; <br />        } <br />        return $result; <br />    } <br />} 


// 使用例子 
$records = array( <br />    array( <br />        'id' => 2135, <br />        'first_name' => 'John', <br />        'last_name' => 'Doe'<br />    ), <br />    array( <br />        'id' => 3245, <br />        'first_name' => 'Sally', <br />        'last_name' => 'Smith'<br />    ), <br />    array( <br />        'id' => 5342, <br />        'first_name' => 'Jane', <br />        'last_name' => 'Jones'<br />    ), <br />    array( <br />        'id' => 5623, <br />        'first_name' => 'Peter', <br />        'last_name' => 'Doe'<br />    ) <br />); <br />$firstNames = array_column($records, 'first_name'); <br />print_r($firstNames); 

/* 
Array 

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

*/


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn