如何在一个html表中显示两个php数组,不包括重复项

时间:2015-08-19 11:12:01

标签: php html arrays

我的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>

怎么可以这样做?

1 个答案:

答案 0 :(得分:2)

您可以创建一个数组,在日期编制索引,并使用正确的值填充它,然后迭代数组以构建您的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>