我正在尝试检查在特定时间范围内预订了多少活动。所以,我试图创建一个数组,time_stamp作为一个数组和space value一个值,如下所示:$数据<pre>Array( [0] => stdClass Object ( [id] => 7 [start] => 2019-06-30 [end] => 2019-06-30 [start_time] => 11:00:00 [end_time] => 12:00:00 [hall_space] => 2 ) [1] => stdClass Object ( [id] => 9 [start] => 2019-06-30 [end] => 2019-06-30 [start_time] => 11:00:00 [end_time] => 12:00:00 [hall_space] => 2 ))</pre所以,创建数组$booked = array();foreach($data as $dk => $dv){ $time_stamp = strtotime($dv->start.' '.$dv->start_time).'_'.strtotime($dv->end.' '.$dv->end_time).'_'.$dk; $booked[$time_stamp] = $dv->rink_space;}因此,这里存储的数据如下:<pre>Array( [1561892400_1561896000_0] => 2 [1561892400_1561896000_1] => 2)</pre>但是,如果我删除这部分,.'_'.$dk它将用第二个索引替换第一个索引并仅保存一个索引,如下所示:<pre>Array( [1561892400_1561896000] => 2)</pre>在这种情况下,如果出现相同的索引,而不是替换,我想添加值,使值变为 4 而不是 2,如下所示:<pre>Array( [1561892400_1561896000] => 4)</pre>
1 回答
慕桂英3389331
TA贡献2036条经验 获得超8个赞
有几种方法可以解决它,一个简单的方法是检查值是否存在(使用isset()),如果存在,只需将其添加进去,如果不存在,则将其设置为新值...
$booked = array();
foreach($data as $dk => $dv){
$time_stamp = strtotime($dv->start.' '.$dv->start_time).'_'.strtotime($dv->end.' '.$dv->end_time);
if ( isset($booked[$time_stamp]) ) {
$booked[$time_stamp] += $dv->rink_space;
}
else {
$booked[$time_stamp] = $dv->rink_space;
}
}
(我已经删除了时间戳的结尾,这是我假设您试图避免这样做的)。
- 1 回答
- 0 关注
- 137 浏览
添加回答
举报
0/150
提交
取消