[英]How to display two php arrays in one html table excluding the duplicates
我的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->day_of_week
对应的$this_week->average_order
,类似地,在第三列中,有与$this_week->day_of_week
对应的$last_week->average_order
。
一般示例:假设$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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.