1

我对数据库获取的结果有点挣扎

假设我有一些行

   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'))
4

1 回答 1

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变量中定义键。为了使代码具有可读性和可管理性,对一般结构进行评论就足够了。

于 2012-04-07T22:49:35.547 回答