我想知道PHP同一表中不同ID的两个日期(表字段中的joinon)之间的差异。我的表格结构如下所示。
显示的日期显示在下面的屏幕截图中提到的字段中。
[![在此处输入图片描述] [2]] [2]
我的php代码在下面提到
<table id="dataTableExample1" class="table table-bordered table-striped table-hover">
<thead>
<tr class="info">
<th class="text-center">Days</th>
<th>Date</th>
<th>Title</th>
<th>Time Interval</th>
<th>Attachment</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$proj_id = $_GET['proj_id'];
$proj = mysql_query("select * from project_historytl where proj_id='$proj_id' order by proj_histl_id desc") or die(mysql_error());
///echo "select * from project_historytl where proj_histl_id='$proj_id' order by proj_histl_id desc";exit();
$s = 0;
while ($getannexure = mysql_fetch_array($proj))
{
$s++;
?>
<tr>
<td class="text-center">Day <?php echo $s;?></td>
<td><?php echo $getannexure['joinon']; ?></td>
<td><?php echo $getannexure['proj_history_title']; ?></td>
<td> </td>
<td><a href="uploads/<?php echo $getannexure['attachment']; ?>" target="_blank">View</a> </td>
<td>
<a href="#" class="btn btn-add btn-sm"><span class="elusive icon-pencil" title="edit"></span><i class="fa fa-pencil"></i></a>
<button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#customer2"><i class="fa fa-trash-o"></i> </button>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
我得到的结果是这种格式enter image description here
答案 0 :(得分:0)
比较两个日期的逻辑如下:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
在您的情况下,如果稍微更改结构以便在开始比较日期之前将所有数组行存储在单个数组中,则可能会更容易。
用以下内容替换while()
循环:
while ($getannexure[] = mysql_fetch_array($proj, MYSQL_ASSOC)){}
运行以下foreach()
:
foreach($getannexure as $id => $row) {
if (!empty($getannexure[$id + 1])) {
$datetime1 = new DateTime($row[$id + 1]['joinon']);
$datetime2 = new DateTime($row[$id]['joinon']);
$interval = $datetime1->diff($datetime2);
$getannexure[$id]['diff'] = $interval->format('%R%a days');
} else {
$getannexure[$id]['diff'] = NULL;
}
}
现在像您一样遍历$getannexure
数组,您将拥有一个可以使用的附加diff
值。