PHP5.3以上 用到了array_map 使用匿名函数进行处理
代码:
<?php function 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:
<?php array (//覆盖掉了 0 => array ( ‘John‘ => ‘Doe‘, ), 1 => array ( ‘Sally‘ => ‘Smith‘, ), ) ?>
时间: 2024-10-08 19:07:08