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