標籤:
PHP5.3以上 用到了array_map 使用匿名函數進行處理
代碼:
<?phpfunction array_col($arr = array(), $idx = 0, $newidx = 0){ if (function_exists(‘array_column‘) && !is_array($idx) && is_bool(strpos($idx, ‘,‘, 1))) { return array_column($arr, $idx, $newidx); } else { return array_map(function($element) use($idx, $newidx) { $ret_arr = array(); $tmp = !is_array($idx) && is_int(strpos($idx, ‘,‘, 1))?explode(‘,‘, $idx):0; $ntmp = !is_array($newidx) && is_int(strpos($newidx, ‘,‘, 1))?explode(‘,‘, $newidx):0; if (empty($tmp)) { return $ret_arr; } $tmpc_idx = count($tmp); $tmpc_newidx = count($ntmp); if (is_int($ntmp) || empty($ntmp)) { for ($i=0; $i < $tmpc_idx; $i++) { $ret_arr[]=$element[$tmp[$i]]; } } else { if ($tmpc_newidx>=$tmpc_idx) { for ($i=0; $i < $tmpc_newidx; $i++) { $ret_arr[$element[$ntmp[$i]]]=$element[$tmp[$i]]; } } } return $ret_arr; }, $arr); }}$a = array( array( ‘id‘ => 2135, ‘first_name‘ => ‘John‘, ‘last_name‘ => ‘Doe‘, ), array( ‘id‘ => 3245, ‘first_name‘ => ‘Sally‘, ‘last_name‘ => ‘Smith‘, ) ); var_export( array_col($a, ‘id,last_name‘,‘first_name,first_name‘)); ?>
output:
<?phparray (//覆蓋掉了 0 => array ( ‘John‘ => ‘Doe‘, ), 1 => array ( ‘Sally‘ => ‘Smith‘, ),)?>
PHP擷取二維數組中的指定若干列【同array_column】