请问如何用键名分组?
程序员文章站
2024-02-18 13:57:34
...
$arr1 = array ('0' => array ('fid' => 1, 'tid' => 1 , 'name' =>'Name2' ),'2' => array ('fid' => 1, 'tid' => 1, 'name' =>'Name1' ),'1' => array ('fid' => 1, 'tid' => 5 , 'name' =>'Name3' ),'3' => array ('fid' => 1, 'tid' => 7 , 'name' =>'Name4' ),'4' => array ('sid' => 2, 'tid' => 9, 'name' =>'Name5' ),'5' => array ('cid' => 2, 'tid' => 9, 'name' =>'Name5' ));
请问有什么最快的方法可以以键名fid,sid,cid分组。
回复讨论(解决方案)
$arr1 = array ('0' => array ('fid' => 1, 'tid' => 1 , 'name' =>'Name2' ),'2' => array ('fid' => 1, 'tid' => 1, 'name' =>'Name1' ),'1' => array ('fid' => 1, 'tid' => 5 , 'name' =>'Name3' ),'3' => array ('fid' => 1, 'tid' => 7 , 'name' =>'Name4' ),'4' => array ('sid' => 2, 'tid' => 9, 'name' =>'Name5' ),'5' => array ('cid' => 2, 'tid' => 9, 'name' =>'Name5' ));foreach($arr1 as $v) { $k = key($v); $res[$k][] = $v;}print_r($res);
Array( [fid] => Array ( [0] => Array ( [fid] => 1 [tid] => 1 [name] => Name2 ) [1] => Array ( [fid] => 1 [tid] => 1 [name] => Name1 ) [2] => Array ( [fid] => 1 [tid] => 5 [name] => Name3 ) [3] => Array ( [fid] => 1 [tid] => 7 [name] => Name4 ) ) [sid] => Array ( [0] => Array ( [sid] => 2 [tid] => 9 [name] => Name5 ) ) [cid] => Array ( [0] => Array ( [cid] => 2 [tid] => 9 [name] => Name5 ) ))
考虑到各成员数组的键名排列可能不一致,即 sid 可能在 name 后面
可将
$k = key($v);
改为
$k = key(array_intersect_key(array('fid' => '', 'sid' => '', 'cid' => ''), $v));
推荐阅读