不用PHP自带的array_column函数实现同样的功能
<?php /** * Created by PhpStorm. * User: 123456 * Date: 2018/9/25 * Time: 19:39 */ $records = array( array( 'id' => 2135, 'first_name' => 'John', 'last_name' => 'Doe', ), array( 'id' => 3245, 'first_name' => 'Sally', 'last_name' => 'Smith', ), array( 'id' => 5342, 'first_name' => 'Jane', 'last_name' => 'Jones', ), array( 'id' => 5623, 'first_name' => 'Peter', 'last_name' => 'Doe', ) ); p(array_column2($records,null,'id')); /** * 模仿array_column函数1 * @param $arr * @param $column * @param NULL $index_key */ function array_column2($arr,$column,$index_key=NULL){ if ($column && !$index_key){ foreach ($arr as $key=>$val){ $data[] = $val[$column]; } } if ($index_key){ foreach ($arr as $key=>$val){ $data[$val[$index_key]] = $column ? $val[$column] : $val; } } return $data; } p(array_column3($records,null,'id')); /** * 模仿array_column函数2 * @param $arr * @param $column_key * @param null $index_key */ function array_column3($arr,$column_key,$index_key=null){ $data = array_map(function($d) use ($column_key,$index_key){ // p($d); if ($column_key && ! $index_key){ return $d[$column_key]; } if ($index_key){ return [$d[$index_key]=>($column_key === null) ? $d : $d[$column_key]]; } },$arr); $tmp=[]; if ($index_key){ foreach ($data as $key=>$val){ $tmp[key($val)] = current($val); } $data = $tmp; } return $data; } function p($data){ echo '<pre>'; print_r($data); echo '</pre>'; }