PHP官方在5.5之后提供了一个内置函数array_column,如果有一个数组是类似这样的:
$dummy_array = array(
0 => array(
'tom' => 1,
'jerry' => 2,
),
1 => array(
'tom' => 3,
'jerry' => 4,
),
2 => array(
'tom' => 5,
'jerry' => 6,
),
);
想抽取数据内层当中的tom字段,生成一个新数组怎么办?代码如下:
array_column($dummy_array,'tom');
这就可以了。
兼容PHP低版本的array_column函数
但如果当前公司的php开发环境很低,没有array_column这个自带函数怎么办呢?这里有一款兼容php低版本的array_column函数,是php脚本实现的,代码贴在这里:
/** * 兼容低版本php的array_column方法 */
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;
}
}
这段代码当中的function_exists是判断函数预定义状况的,可以酌情去除。这样即便是PHP版本低,也能使用array_column方法,把它导进项目里吧。