php array_column函数封装
array_column函数只支持php5.5.0以上版本,所以这里要封装下,这样可以兼容用法
if (!function_exists("array_column")) { function array_column($array, $val_col, $key_col) { if($key_col==null) { return array_map(function ($element) use ($val_col) { return $val_col==null?$element:$element[$val_col]; } , $array); } else { $_array=array(); foreach ($array as $_key=>$_val) { $_array[$_val[$key_col]]=$val_col==null?$_val:$_val[$val_col]; } return $_array; } } }
注意事项:
$arr = array( array( 'id' => 1, 'first_name' => 'John', 'last_name' => 'Does', ), array( 'id' => 2, 'first_name' => 'Sally', 'last_name' => 'Smith', ), array( 'id' => 3, 'first_name' => 'Jane', 'last_name' => 'Jones', ), array( 'id' => 4, 'first_name' => 'Peter', 'last_name' => 'Doe', ) ); print_r(array_column($arr,'first_name')); //运行结果: /* Array ( [0] => John [1] => Sally [2] => Jane [3] => Peter ) */ print_r(array_column($arr,'first_name','last_name')); //运行结果: /* Array ( [Does] => John [Smith] => Sally [Jones] => Jane [Doe] => Peter ) */ print_r(array_column($arr, null, 'last_name')); //运行结果: /* Array ( [Does] => Array ( [id] => 1 [first_name] => John [last_name] => Does ) [Smith] => Array ( [id] => 2 [first_name] => Sally [last_name] => Smith ) [Jones] => Array ( [id] => 3 [first_name] => Jane [last_name] => Jones ) [Doe] => Array ( [id] => 4 [first_name] => Peter [last_name] => Doe ) ) */