答案 0 :(得分:1)
这是一个可能的解决方案。数据库表已命名为tborderdetail
:
/* I get data using json object (for convenience): */
$arr = [];
$s = "SELECT product_name, SUM(amount) AS amount, DATE_FORMAT(order_date,'%d %b %Y') AS order_date FROM tborderdetail GROUP BY product_name, DATE_FORMAT(order_date,'%d %b %Y') ORDER BY order_date DESC";
$q1 = mysqli_query($con,$s);
while($row = mysqli_fetch_assoc($q1)){$arr[] = $row;}
$str = json_encode($arr);
$data = json_decode($str);
/* Populate three arrays that will be used to create the required table */
$arr_dates = [];
$arr_products = [];
$arr_date_product_amount = [];
foreach($data as $v){
if(!in_array($v->order_date, $arr_dates)){ $arr_dates[] = $v->order_date; }
if(!in_array($v->product_name, $arr_products)){ $arr_products[] = $v->product_name;}
$dpv = str_replace(' ','',$v->product_name.$v->order_date);
$arr_date_product_amount[$dpv] = $v->amount;}
/* Start outputting the table and the top row */
echo '<table><tr><td>Products</td>';
foreach($arr_dates as $dt){ echo '<td>Sale on '.$dt.'</td>'; }
echo '</tr>';
/* Output the other rows of the table: */
foreach($arr_products as $pt){
echo '<tr><td>'.$pt;
foreach($arr_dates as $dt){
$dpv = str_replace(' ','',$pt.$dt);
/* Ensure no errors due to missing values */
echo '<td>'; if(array_key_exists($dpv,$arr_date_product_amount)){echo $arr_date_product_amount[$dpv];}
echo '</td>';}
echo '</tr>';}
echo '</table>';