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

请问如何用键名分组?

WBOY
Release: 2016-06-23 14:38:26
Original
743 people have browsed it

$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' ));
Copy after login


请问有什么最快的方法可以以键名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);
Copy after login
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                )        ))
Copy after login

考虑到各成员数组的键名排列可能不一致,即 sid 可能在 name 后面
可将
  $k = key($v);
改为
  $k = key(array_intersect_key(array('fid' => '', 'sid' => '', 'cid' => ''), $v));

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template