doupai8095 2013-02-18 22:58
浏览 13
已采纳

使用SQL将行元素分组到一列中

My current table is fetching content from the database like this but I would like to combine the rows so that all the Room Preference's are displayed in one row rather than over several. How can I go about doing this? As a result the table below would have only two rows.

The Room Preference information is being inferred from ts_roompref.

enter image description here

Here is my code so far:

    $sql = "SELECT 
            *
    FROM ts_request
    INNER JOIN ts_day
    ON ts_request.day_id = ts_day.id
    INNER JOIN ts_period
    ON ts_request.period_id = ts_period.id
    INNER JOIN ts_allocation
    ON ts_request.id = ts_allocation.request_id
    INNER JOIN ts_roompref
    ON ts_request.id = ts_roompref.request_id
    WHERE ts_request.round=:round
    AND ts_request.dept_id=:dept
    ORDER BY ts_request.module_id ASC";
    }
    $stm = $pdo->prepare( $sql );
    $stm->execute( array( ':round' => 'P', ':dept' => $loggedin_id  ) );
    $rows = $stm->fetchAll();   

        foreach ($rows as $row) 
    {               
    echo '<tr align="center">'; 
    echo '<td>'.$row['module_id'].'</td>';
    echo '<td>'.$row['day'].'</td>';    
    echo '<td>'.$row['period'].'</td>';
    echo '<td>';
    if ($row['room_id']=="0")
    {
    echo "Any";
    }
    else
    {
    echo $row['room_id'];
    }
    echo '</td>';           
    echo '<td>'.$row['status'].'</td>';
    echo '</tr>';
  • 写回答

2条回答 默认 最新

  • duandao1931 2013-02-18 23:06
    关注

    Well, I guess your trying to do it in SQL, but if you wanted to do it in your PHP you could loop over the rows watching for changes to Module Code. Pseudo code something like...

    $newrows = array()
    $tmpCode = ""
    foreach $rows as $row
       if $tmpCode != $row['module_code'] {
           $tmpCode = $row['module_code']
    
           $newrows[] = $row 
       } else {
           $newrows[count($newrows) - 1]['room_preference'] .= $row['room_preference']
       }
    }
    

    ...rough, but you get the idea.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?