Here’s an example using the first three rows of data -
<?php
// fake some data that would be fetched from the sql query
$stmt = [];
$stmt[] = ['date'=>'14 Feb 2022', 'order id'=>'1134', 'order total'=>'510', 'payment'=>'10', 'p date'=>'2022-02-15'];
$stmt[] = ['date'=>'14 Feb 2022', 'order id'=>'1134', 'order total'=>'510', 'payment'=>'500', 'p date'=>'2022-02-15'];
$stmt[] = ['date'=>'12 Mar 2022', 'order id'=>'1274', 'order total'=>'230', 'payment'=>'230', 'p date'=>'2022-03-15'];
// array to hold the indexed/pivoted data
$data = [];
// index/pivot the data using the order id as the main array index
foreach($stmt as $row)
{
$data[ $row['order id'] ][] = $row;
}
// produce the output -
$output = '';
foreach($data as $order_id=>$arr1)
{
// at this point, you have an $order_id
// count($arr1) will tell you how many rows there are going to be in the output section,
// that can be used for the rowspan attribute in date, order id, and order total columns
$rs = count($arr1);
$first = true;
foreach($arr1 as $row)
{
// start tr
$output .= "<tr>";
// output the initial rowspan column(s)
if($first)
{
// date, order id, order total
$output .= "<td rowspan='$rs'>{$row['date']}</td>";
$output .= "<td rowspan='$rs'>{$row['order id']}</td>";
$output .= "<td rowspan='$rs'>{$row['order total']}</td>";
}
// output the unique row data
$output .= "<td>{$row['payment']}</td><td>{$row['p date']}</td>";
// output the final rowspan column(s)
if($first)
{
// not used
//$output .= "<td rowspan='$rs'>...</td>";
}
$first = false;
// end tr
$output .= "</tr>";
}
}
?>
<style>
table, th, td {
border: 1px solid black;
}
</style>
<table>
<tr>
<th>Order Date</th>
<th>Order ID</th>
<th>Order Total</th>
<th>Payment</th>
<th>Payment Date</th>
</tr>
<?php echo $output; ?>
</table>
Output:
Order Date |
Order ID |
Order Total |
Payment |
Payment Date |
14 Feb 2022 |
1134 |
510 |
10 |
2022-02-15 |
|
|
|
500 |
2022-02-15 |
12 Mar 2022 |
1274 |
230 |
230 |
2022-03-15 |