循环中的PHP列表

时间:2011-02-08 16:51:17

标签: php sql foreach for-loop do-while

如何将列表放入while循环?

PHP:

> $q = $db->query("SELECT * FROM
> bs_events LEFT JOIN bs_reservations ON
> bs_reservations.id_event = bs_events.id   
> GROUP BY bs_reservations.id_event 
> ORDER BY bs_events.eventDate ASC LIMIT 20");

HTML TABLE:

> while($r = $q->fetch_array(MYSQLI_ASSOC)):  
> echo '<tr>';
> echo '<td>' . $r['title'] . '</td>';  
> echo '<td>' . date('d/M/Y', strtotime($r['eventDate'])) . ' / ' . $r['eventTime'] . '</td>';  
> echo '<td>' . $r['location'] . '</td>';  
> echo '<td>' . array($r['username']) .'</td>';  
> echo '<td ></td>';  
> echo '<td ></td>';  
> echo '</tr>';  
> endwhile;

上面的代码将输出

TITLE        DATE/TIME      LOCATION    USERNAME
=================================================
1       dd/mm/yyy / hh:mm   location    username
1       dd/mm/yyy / hh:mm   location    username1 
1       dd/mm/yyy / hh:mm   location    username2 
2       dd/mm/yyy / hh:mm   location    username   

我想要输出

TITLE        DATE/TIME      LOCATION    USERNAME
=================================================
1       dd/mm/yyy / hh:mm   location    username, username1, username2  
2       dd/mm/yyy / hh:mm   location    username 

或者我需要在echo '<td>' . array($r['username']) .'</td>';

上加上foreach

2 个答案:

答案 0 :(得分:2)

查看GROUP_CONCAT

答案 1 :(得分:2)

这样的东西
SELECT title,
       event_date,
       event_time,
       location,
       GROUP_CONCAT(username SEPARATOR ', ') AS username
  FROM bs_events 
  LEFT JOIN bs_reservations
         ON bs_reservations.id_event = bs_events.id   
 GROUP BY bs_reservations.id_event 
          bs_events.title,
          bs_events.event_date,
          bs_events.event_time,
          bs_events.location
 ORDER BY bs_events.eventDate ASC LIMIT 20

修改

为用户名

添加了别名