0

我正在使用 php + sql。现在我有一个这样的表:

user_id  word
-------------
 u1       w1
 u1       w2
 u2       w1
 u2       w3

我想在数据库中查询按用户分组的数据。期望的结果应该是一个分层数组,比如

array("u1"=>array("0"=>"w1', "1"=>"w2"), "u2"=>array("0"=>"w1", "1"=>"w3"))

我怎样才能做到这一点?

编辑

我只写了一些普通的sql之类的

select * from DB order by user

恐怕它没有什么接近的。

4

3 回答 3

1

This is a basic example but you MUST USE PDO instead of mysql_*

Try below one. It will solve your problem

$query = "SELECT * FROM tblwords";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
    $userId = $row['user_id'];
    $arr[$userId][] = $row['word'];
}
echo "<pre>";print_r($arr);

Output

Array
(
    [u1] => Array
        (
            [0] => w1
            [1] => w2
        )

    [u2] => Array
        (
            [0] => w1
            [1] => w3
        )

)
于 2013-05-24T15:00:48.037 回答
1

是的,你可以做到,我没有检查,但请尝试,

$query = mysql_query("SELECT * FROM tableName WHERE 1 GROUP BY user_id");
While($data = mysql_fetch_object($query)){
     $get_data[] = $data ;
}

if($get_data){
    foreach($get_data as $val){
        $query = mysql_query("SELECT * FROM tableName WHERE user_id = '".$val['user_id']."'");
        while($data_new = mysql_fetch_assoc($query)){
            $val['user_id'];
            $res[] = $data_new ;
        }
        $userID = $val['user_id'] ;
        $array[][$userID] = $res ;
    }
}
print_r($array);
于 2013-05-24T08:37:11.307 回答
0

我不确定,但我知道你不能。

但你可以得到这样的结果;

SELECT user_id
    , GROUP_CONCAT(DISTINCT word
        ORDER BY wordDESC SEPARATOR ',') as words
FROM table_name
GROUP BY user_id

结果;

user_id | words
  u1    | w1,w2
  u2    | w1,w3
于 2013-05-24T07:17:16.553 回答