您好,欢迎访问一九零五行业门户网

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

php5.5发布,其中增加了一个新的数组函数array_column,感觉不错的!
但是低版本php要使用,得自己实现:
if(!function_exists('array_column')){
function array_column($input, $columnkey, $indexkey=null){
$columnkeyisnumber = (is_numeric($columnkey)) ? true : false;
$indexkeyisnull = (is_null($indexkey)) ? true : false;
$indexkeyisnumber = (is_numeric($indexkey)) ? true : false;
$result = array();
foreach((array)$input as $key=>$row){
if($columnkeyisnumber){
$tmp = array_slice($row, $columnkey, 1);
$tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null;
}else{
$tmp = isset($row[$columnkey]) ? $row[$columnkey] : null;
}
if(!$indexkeyisnull){
if($indexkeyisnumber){
$key = array_slice($row, $indexkey, 1);
$key = (is_array($key) && !empty($key)) ? current($key) : null;
$key = is_null($key) ? 0 : $key;
}else{
$key = isset($row[$indexkey]) ? $row[$indexkey] : 0;
}
}
$result[$key] = $tmp;
}
return $result;
}
}
// 使用例子
$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'
)
);
$firstnames = array_column($records, 'first_name');
print_r($firstnames);
/* 
array 

    [0] => john 
    [1] => sally 
    [2] => jane 
    [3] => peter 

*/
其它类似信息

推荐信息