首页 > 解决方案 > 在仪表板中显示数字,每年从 1 开始

问题描述

我有一个表格,我希望在我的 .php 文件中显示,因为它将显示每行的每个数字,但是当涉及到全新的一年时,它将再次更改为从 1 开始。

.php 文件 html 代码:

<table id="example">
      <thead>
             <tr>
             <th style="width: 40px">Year</th>
             <th style="width: 40px">Id</th>
             </tr>
     </thead>
<tbody>
<?php
include('include/config1.php');
$query = "SELECT * from table ORDER BY Id DESC";
$result = mysqli_query($db, $query);
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php
     if($row['status']!=3){ //display the year from the date according to status
       echo date("Y",strtotime($row['sdate'])); }
     else{
       echo date("Y",strtotime($row['ssdate']));
     } ?>
     //the years are the same for both columns in each row
</td>

<td>//The ID that auto starts from 1 every year with an increment of 1 to the newest (not the same as the unique id from the table </td>

<?php}?>
</tbody>
</table>

我必须实现什么样的 javascript 函数才能使其工作?

注意:所有插入到 MySQL 表中的数据不会从数据库中删除,状态只会更改为删除,仅此而已。

标签: javascriptphphtmlmysql

解决方案


首先,如果您希望您的记录年复一年地排序,您还必须按date字段排序!

"SELECT * from table ORDER BY sdate,Id DESC";

其次,您必须循环记住上一年,并将其与当前进行比较。如果不同,则将您的 ID 重置为1

<?php
    include('include/config1.php');
    $query = "SELECT * from table ORDER BY sdate, Id DESC";
    $result = mysqli_query($db, $query);

    $currentYear = null;
    $data = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $year = ($row['status'] == 3) ? date("Y", strtotime($row['ssdate'])) : date("Y", strtotime($row['sdate']));

        $data[$year][] = $row;                     
    }
?>

<table id="example">
<thead>
    <tr>
        <th style="width: 40px">Year</th>
        <th style="width: 40px">Id</th>
        <th style="width: 80px">Machine No</th>
        <th style="width: 80px">Project Name</th>
        <th style="width: 80px">PIC</th>
        <th style="width: 80px">Purpose of Service</th>
    </tr>
</thead>
<tbody>
<?php 
    foreach ($data as $year => $oneYear) {
        for ($i = count($oneYear); $i >= 1; $i--) {
?>
    <tr>
        <td><?= $year ?></td>
        <td><?= $i ?></td>
        <td><?= $oneYear[$i]['Machine_No']; ?></td>
        <td><?= $oneYear[$i]['projectName']; ?></td>
        <td><?= $oneYear[$i]['pic']; ?></td>
        <td><?= substr(str_replace('\r\n', "\r\n", $row['Purpose_of_Service']), 0, 50); ?></td>
    </tr>
<?php
        }
    }
?>
</tbody>
</table>

推荐阅读