多维数组提取某一字段转换为一维数组 array_column

array_column 为PHP自带函数 需要  (PHP 5 >= 5.5.0, PHP 7)

当PHP版本的低时 可用自定义行数来实现

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;
}

posted @ 2016-07-27 09:42  121686076  阅读(505)  评论(0编辑  收藏  举报