1

我有以下用于在 PHP 中显示 MySQL 查询的语法:

 function get_dayssincecapture($db)  
  {    
    $result = $db->query("SELECT DATEDIFF(now(), sarrive)as days,count(loadnumber) as loads from v2loads where  adminstatus='captured' group by DATEDIFF(now(), sarrive) "); 
    return $result; 
  } 
  $dayssincecapture = get_dayssincecapture($db); 

显示语法:

<table border=1>
    <tr>
    <? while($row = $dayssincecapture->fetch(PDO::FETCH_ASSOC)) { ?>
    <td><? echo $row['days']; ?><br><? echo $row['loads']; ?></td>
    <? } ?>
    </tr>
</table>

这会产生以下屏幕输出

在此处输入图像描述

如何通过表语法进行更改,以便将天字段作为行标题,将负载字段作为表的第二行?

所以我想要的是:

在此处输入图像描述

一如既往地感谢,

4

3 回答 3

5

尝试:

<?php
$dayssincecapture = get_dayssincecapture($db); 
$data = array('days' => array(), 'loads' => array());

while($row = $dayssincecapture->fetch(PDO::FETCH_ASSOC)) {
    $data['days'][]  = $row['days'];
    $data['loads'][] = $row['loads'];
}
?>

<table style="border: 1px solid #000">
    <tr>
        <td>Days</td>
        <?php foreach ( $data['days'] as $day ) { ?>
            <td><?php echo $day; ?></td>
        <?php } ?>
    </tr>
    <tr>
        <td>Loads</td>
        <?php foreach ( $data['loads'] as $load ) { ?>
            <td><?php echo $load; ?></td>
        <?php } ?>
    </tr>
</table>
于 2013-01-11T11:19:49.267 回答
1

如果您想在 MySQL 中执行这种类型的转换,那么您将旋转数据。MySQL 没有数据透视函数,但您可以使用带有CASE语句的聚合函数来复制它:

select 
  count(case when DATEDIFF(now(), sarrive) = 1 then loadnumber end) as Day_1,
  count(case when DATEDIFF(now(), sarrive) = 2 then loadnumber end) as Day_2,
  count(case when DATEDIFF(now(), sarrive) = 3 then loadnumber end) as Day_3,
  count(case when DATEDIFF(now(), sarrive) = 4 then loadnumber end) as Day_4,
  count(case when DATEDIFF(now(), sarrive) = 5 then loadnumber end) as Day_5,
  count(case when DATEDIFF(now(), sarrive) = 6 then loadnumber end) as Day_6,
  count(case when DATEDIFF(now(), sarrive) = 7 then loadnumber end) as Day_7
from v2loads
where adminstatus='captured' 

您还可以在准备好的语句中编写此代码以动态创建它,因为值将是未知的。

于 2013-01-11T11:24:01.433 回答
1

你可以试试:

<?php

while($row = $dayssincecapture->fetch(PDO::FETCH_ASSOC)) {
    $days_row .= "<td>" . $row['days'] . "</td>";
    $loads_row .= "<td>" . $row['loads'] . "</td>";
}

?>
<table> 

  <tr>
    <td>Days</td>
    <?php echo $days_row; ?>
  </tr>
  <tr>
    <td>Loads</td>
    <?php echo $loads_row; ?>
  </tr>
</table>
于 2013-01-11T11:38:01.883 回答