我想要这样的桌子 具有相同日期分组的每一行都被尝试了group_concat和group_by,但是它不起作用,我希望php中的一些过滤器将具有相同日期的行合并在一起
我的代码:
while ($row = mysqli_fetch_array($result)) {
$start_res = strtotime($row['from_date']);
$end_res = strtotime($row['to_date']);
for ($res = $start_res; $res <= $end;$res+=86400) {
$res_date = date("m/d/Y", $res);
$startres = strtotime($res_date);
if ($startres >= $start_res && $startres<=$end_res) {
?>
<tr>
<td><?= $res_date ?> </td>
<td><?= $row['1'] ?> </td>
<td><?= $row['2'] ?> </td>
<td><?= $row['3'] ?> </td>
<td><?= $row['4'] ?> </td>
<td><?= $row['5'] ?> </td>
<td><?= $row['6'] ?> </td>
<td>0 </td>
<td style="background-color:gold"> 0</td>
<td>0 </td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<?php }}}?>
$sql = "
SELECT * FROM mytable
WHERE hotel_id = '" . $hotel_id . "'
and from_date between '" . $date . "' and '" . $end_date . "'
or to_date between '" . $date . "' and '" . $end_date . "'
ORDER BY from_date asc
";
$result = mysqli_query($con, $sql);
答案 0 :(得分:0)
根据您的表结构,用PHP进行此操作可能最简单。要在SQL中执行此操作,需要一个日历表将JOIN连接到每一行。因此,您需要汇总每个日期的值,然后输出它们。注意,我更喜欢将列名作为数组索引使用,因为这样更容易查看正在执行的操作:
$data = array();
// collate the data
while ($row = mysqli_fetch_array($result)) {
$start_res = strtotime($row['from_date']);
$end_res = strtotime($row['to_date']);
for ($res = $start_res; $res <= $end && $res <= $end_res; $res += 86400) {
if (!isset($data[$res])) $data[$res] = array('totals' => 0, 'agent' => 0, 'direct' => 0, 'over_agent' => 0, 'over_hotel' => 0, 'allotment' => 0);
$data[$res]['totals'] += $row['totals'];
$data[$res]['agent'] += $row['agent'];
$data[$res]['direct'] += $row['direct'];
$data[$res]['over_agent'] += $row['over_agent'];
$data[$res]['over_hotel'] += $row['over_hotel'];
$data[$res]['allotment'] += $row['allotment'];
}
}
// sort the data by date
ksort($data);
// now display the combined data
foreach ($data as $res_date => $row) {
?>
<tr>
<td><?= date('m/d/Y', $res_date) ?> </td>
<td><?= $row['totals'] ?> </td>
<td><?= $row['agent'] ?> </td>
<td><?= $row['direct'] ?> </td>
<td><?= $row['over_agent'] ?> </td>
<td><?= $row['over_hotel'] ?> </td>
<td><?= $row['allotment'] ?> </td>
<td>0</td>
<td style="background-color:gold"> 0</td>
<td>0 </td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<?php
}