假设php脚本中有两个数组:
foreach( $orders_this_week as $this_week ){
echo $this_week->day_of_week;
echo $this_week->average_order;
}
第二个是
foreach( $orders_last_week as $last_week ){
echo $last_week->day_of_week;
echo $last_week->average_order;
}
我想在3列表中显示上述数组的结果,第一列将包含星期几,例如:
$last_week->day_of_week
或$this_week->day_of_week
和将不重复,意味着如果$last_week->day_of_week
有星期日,$this_week->day_of_week
也有星期日,那么在HTML表的第一列将有一个星期日。
第二列是$this_week->average_order
,对应$this_week->day_of_week
,第三列是$last_week->average_order
,对应$this_week->day_of_week
。
一般示例:让$this_week
拥有{[sunday, monday],[5,4]}
$ last_week
有{[sunday, tuesday], [3,5]}
因此输出的HTML表将看起来像
<table border="1" width="300px">
<tr>
<th>Sunday</th>
<td>5</td>
<td>3</td>
</tr>
<tr>
<th>monday</th>
<td>4</td>
<td></td>
</tr>
<tr>
<th>tuesday</th>
<td></td>
<td>5</td>
</tr>
</table>
这是怎么做到的?
您可以创建一个数组,按天索引,并用正确的值填充它,然后迭代该数组以构建html表:
$days = [
'Monday'=>[],
'Tuesday'=>[],
'Wednesday'=>[],
//... rest of the days here
];
foreach( $orders_this_week as $this_week ){
$days[$this_week->day_of_week]['this_week']=$this_week->average_order;
}
foreach( $orders_last_week as $last_week ){
$days[$last_week->day_of_week]['last_week']=$last_week->average_order;
}
?>
<table>
<?php foreach ($days as $day => $value): if(!empty($value)):?>
<tr>
<td><?php echo $day;?></td>
<td><?php echo isset($value['this_week'])?$value['this_week']:''?></td>
<td><?php echo isset($value['last_week'])?$value['last_week']:''?></td>
</tr>
<?php endif; endforeach;?>
</table>