对于一个二维数组:
$arr = [ ['num'=>2019,'name'=>'Jack','age'=>19], ['num'=>2019,'name'=>'Jone','age'=>18], ['num'=>2020,'name'=>'Marry','age'=>20]];
我们想获取以num值为键php二维数组怎么使用,其php二维数组怎么使用他值为该键php二维数组怎么使用的值php二维数组怎么使用的数组
可以使用下面函数实现:
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 ) ))