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方法,把它導進項目裡吧。