php 多个数组根据指定键值分组方法:
$array:要分组的数组
$key:根据的键名
function array_group($array,$key) { $result = []; foreach($array as $k=>$v){ $result[$v[$key]][] = $v; } return $result; }
演示数组:
$arr = [ [ 'city' => 'beijing', 'name' => '大哥' ], [ 'city' => 'shanghai', 'name' => '二哥' ], [ 'city' => 'guangzhou', 'name' => '三哥' ], [ 'city' => 'beijing', 'name' => '四哥' ] ];
调用方法:
var_dump(array_group($arr,'city'));
输出数组:
array(3) { ["beijing"] => array(2) { [0] => array(2) { ["city"] => string(7) "beijing" ["name"] => string(6) "大哥" } [1] => array(2) { ["city"] => string(7) "beijing" ["name"] => string(6) "四哥" } } ["shanghai"] => array(1) { [0] => array(2) { ["city"] => string(8) "shanghai" ["name"] => string(6) "二哥" } } ["guangzhou"] => array(1) { [0] => array(2) { ["city"] => string(9) "guangzhou" ["name"] => string(6) "三哥" } } }
声明:本文为原创文章,版权归主机之家测评所有,欢迎分享本文,转载请保留出处!