0

I'm using php + sql. Now I've a table like this:

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

And I want to query the database for the data grouped by user. The desired result should be a hierarchical array, like

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

How can I do that?

Edit

I have only wrote some ordinary sql's like

select * from DB order by user

And I'm afraid it's nothing close.

1
  • Have you wrote any SQL query yet for this? Commented May 24, 2013 at 7:16

3 Answers 3

1

Yes you can do it, I haven't checked but please try,

$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);
Sign up to request clarification or add additional context in comments.

1 Comment

Note that there is another answer by @NullVoid that has a better performance.
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
        )

)

3 Comments

Thanks. I think your answer is the same as Purushottam's and I will select his as the answer for he seems to be a new guy here. And +1 for your elegant illustration.
Definitely. We should encourage new guys. I am glad that your problem has been resolved. I just read his answer and my answer is more accurate in case of performance. I have used only one loop while he's executing loop 3 times.
That's right. I've to confess that your answer is more elegant in both script and performance.
0

i'm not sure but as i know you can't.

but you can get the result like this;

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

result;

user_id | words
  u1    | w1,w2
  u2    | w1,w3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.