将数组放在一起分组

时间:2012-04-07 22:41:41

标签: php arrays grouping

我对数据库提取的结果感到有些不满

让我说我有一些行

   array('id'=>1, 'surname'=>'rossi', 'name'=>'mario', 'group'=>'admin'), 
   array('id'=>2, 'surname'=>'rossi', 'name'=>'giovanni', 'group'=>'user'), 
   array('id'=>3, 'surname'=>'verdi', 'name'=>'luigi', 'group'=>'user'), 
   array('id'=>4, 'surname'=>'verdi', 'name'=>'franco', 'group'=>'guest'), 
   array('id'=>5, 'surname'=>'bianchi', 'name'=>'mario', 'group'=>'guest') 

现在我需要做什么才能将这5行放入分组数组中?

示例:

user = array(
   array('id'=>2, 'surname'=>'rossi', 'name'=>'giovanni', 'group'=>'user'), 
   array('id'=>3, 'surname'=>'verdi', 'name'=>'luigi', 'group'=>'user'))
guest = array(
   array('id'=>4, 'surname'=>'verdi', 'name'=>'franco', 'group'=>'guest'), 
   array('id'=>5, 'surname'=>'bianchi', 'name'=>'mario', 'group'=>'guest')) 
admin = array(
   array('id'=>1, 'surname'=>'rossi', 'name'=>'mario', 'group'=>'admin'))

1 个答案:

答案 0 :(得分:5)

// get query result
$result = mysql_query(...);

// prepare the target array
// it will hold user groups having group name as key
// eg. "user" => Array(), "guest" => Array()
$users = Array();

// whlile fetching rows from the result, add each row into $row["group"] key of target
while($row = mysql_fetch_assoc($result))
   $users[$row["group"]][] = $row;

// free the mysql result
mysql_free_result($result);

更新:无需在目标$user变量中定义键。为了使代码可读和易于管理,只需评论一般结构即可。