选择所选行的不同

时间:2013-09-05 03:16:22

标签: php mysql database

我正在从两个表中选择行

$a = mysql_query("SELECT a.id, a.id_user, a.id_location, a.id_event, a.date FROM event as a LEFT JOIN rating as b ON a.id_event = b.id_event AND a.id_user = b.id_whos_get_rate WHERE a.id_user <> $log1[id] AND EXISTS ( SELECT 1 FROM event as c WHERE a.id_event = c.id_event AND c.id_user = $log1[id] ) AND b.id IS NULL ORDER BY DATA") ;

然后我收到数组

a.id | a.id_user | a.id_location | a.id_event | a.date ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 2 1 2 20.03.2013 2 3 1 2 20.03.2013 3 4 1 2 20.03.2013 4 12 1 3 20.03.2013 5 13 1 3 20.03.2013 6 14 1 3 20.03.2013

然后我想回应这些值并为每个用户添加无线电,我正在这样做:

<pre>>while($b = mysql_fetch_array($a)){ 
>$place = mysql_query("select * from name_event where id=$b[id_location]");
>$place1= mysql_fetch_array($place);
>echo  $place1[name];
>echo $b[date].;
>echo "id event: ".$b[id_event].;
>$name= mysql_query("select* from users where id='".$b[id_user]."'and id!=$log1[id]");
>$name1= mysql_fetch_array($name);
>if (!empty($name1[login])){
>echo  $name1[login].   ;
>echo "form method ='post' action ='rate.php'
>rate
>input type='radio' name='s' value='$name1[id]|1|$b[id_event]' 
>input type='radio' name='s' value='$name1[id]|2|$b[id_event]' 
>input type='submit' name='submit' value='value'

问题是a.id_event有多个值,我不知道如何更改代码只回显一次a.id_event,然后是所有参与该事件的用户,因为此时它是回声

id_event 2 
id_user 2

id_event 2 
id_user 3

id_event 2 
id_user 4

我希望能像那样工作

id_event 2 
id_user 2
id_user 3
id_user 4

1 个答案:

答案 0 :(得分:0)

只要您的数据按id_event排序,因此值是连续的,我认为最好的答案就是在循环中有一个变量来包含last的id_event并打印id_user如果它被重复。

举个例子:

$last_id_event = null;
while($row = mysql_fetch_array($a)){ // Each row
    if($row['id_event'] != $last_id_event){
        echo "id event: ".$row['id_event'];
        $last_id_event = $row['id_event']
    }
    echo "id user: ".$row['id_user'];
}

编辑:将foreach更改为while(... mysql_fetch_array),这是正确的方法。