Home >Backend Development >PHP Tutorial >请问如何用键名分组?

请问如何用键名分组?

WBOY
WBOYOriginal
2016-06-23 14:38:26751browse

$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));

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn