码迷,mamicode.com
首页 > 编程语言 > 详细

PHP获取二维数组中的指定若干列【同array_column】

时间:2015-08-11 15:34:08      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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‘,
  ),
)
?>

 

PHP获取二维数组中的指定若干列【同array_column】

标签:

原文地址:http://www.cnblogs.com/jso0/p/4720946.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!