对于一个二维数组:
$arr = [ ['num'=>2019,'name'=>'Jack','age'=>19], ['num'=>2019,'name'=>'Jone','age'=>18], ['num'=>2020,'name'=>'Marry','age'=>20] ];
我们想获取以num值为键,其他值为该键的值的数组
可以使用下面函数实现:
function array_group_by($arr, $key) {
$grouped = [];
foreach ($arr as $value) {
$grouped[$value[$key]][] = $value;
}
if (func_num_args() > 2) {
$args = func_get_args();
foreach ($grouped as $key => $value) {
$parms = array_merge([$value], array_slice($args, 2, func_num_args()));
$grouped[$key] = call_user_func_array('array_group_by', $parms);
}
}
return $grouped;
}
$res = array_group_by($arr, 'num');
dump($res);
结果为如下:
Array ( [2019] => Array ( [0] => Array ( [num] => 2019 [name] => Jack [age] => 19 ) [1] => Array ( [num] => 2019 [name] => Jone [age] => 18 ) ) [2020] => Array ( [0] => Array ( [num] => 2020 [name] => Marry [age] => 20 ) ) )
海报
0 条评论
176
相关文章
本站已关闭游客评论,请登录或者注册后再评论吧~