【发布时间】:2012-03-20 18:42:32
【问题描述】:
对于日历,我从数据库中读取开始日期和结束日期,然后 dateRange 函数为每个键创建一个包含一天的数组,如下所示:
$total_dates[]=dateRange('2012-04-01','2012-04-05');
$total_dates[]=dateRange('2012-04-06','2012-04-09');
$total_dates[]=dateRange('2012-04-10','2012-04-15');
$total_dates[]=dateRange('2012-04-17','2012-04-21');
$total_dates[]=dateRange('2012-04-24','2012-04-28');
将输出:
Array (
[0] => Array ( [0] => 2012-04-01 [1] => 2012-04-02 [2] => 2012-04-03 [3] => 2012-04-04 [4] => 2012-04-05 )
[1] => Array ( [0] => 2012-04-06 [1] => 2012-04-07 [2] => 2012-04-08 [3] => 2012-04-09 )
[2] => Array ( [0] => 2012-04-10 [1] => 2012-04-11 [2] => 2012-04-12 [3] => 2012-04-13 [4] => 2012-04-14 [5] => 2012-04-15 )
[3] => Array ( [0] => 2012-04-17 [1] => 2012-04-18 [2] => 2012-04-19 [3] => 2012-04-20 [4] => 2012-04-21 )
[4] => Array ( [0] => 2012-04-24 [1] => 2012-04-25 [2] => 2012-04-26 [3] => 2012-04-27 [4] => 2012-04-28 )
)
现在它应该在包含在数组中并且在空闲日期可用的那些日期输出不可用。每天只能预约一次(目前,我以后也需要像早上和下午一样实现,所以这会交叉)。
逻辑是从第一天到最后一天。如果不是,echo free,如果是,检查是否是这个dateRange的最后一天,如果是,增加子数组的key...
这里是代码,但是如果是最后一个key就不会增加key...
reset($total_dates);
$array_i=0;
for ($i=1;$i<=$this_maxdays_month;$i++) {
if($i<10) {$i2="0".$i;} else {$i2=$i;} //if $i is 1-9, add a leading zero
if($i==1) {$month_begin=date('M',$this_date)." ";} else {$month_begin="";} //if 1st of month add e.g. Jan
if($total_dates[$array_i]) {
if (in_array("$year-month-$i2",$total_dates[$array_i])) {
echo "not available";
// now check if the last key in date range, if yes, increase key -> does not work!
if (key(array_slice($total_dates[$array_i], -1, 1, TRUE))+1==$i) {$array_i++;}
}
else {
echo "available";
}
}
}
PS:我也试过了:
$count_max_array_keys=count($total_dates[$array_i])+1;
if (!array_key_exists($count_max_array_keys,$total_dates[$array_i])) {$array_i++;}
并使用 +1(如第一个示例)...
...有人知道我在这里缺少什么吗??
提前谢谢你!
更新:它应该输出(稍后在日历视图中构建),例如:
1st April 2012: booked
2nd April 2012: booked
3rd April 2012: booked (this is the last date of this dateRange, so increase key)
4th April 2012: (not in array anymore) available
5th April 2012: available
6th April 2012: (is in the next dateRange) booked
...
希望现在更清楚了,谢谢!
更新 2:如果我在与之前的 array_slice 完全相同的位置使用 if ( (count($total_dates[$array_i])-1)+1==$i) {$array_i++;},则会发生以下情况:
row-number $array_i output of the count-statement
1: 0 4
2: 0 4
3: 0 4
4: 0 4
5: 1 3 (this is the last key, but here $array_i should still be 0, as the increase happens after the output, and why is suddenly count only 3?)
6-30: 1 3 (it never increases again)
【问题讨论】:
-
您在这里的实际目标是什么?当您应该使用锤子(MySQL 或任何您的数据库引擎)时,您似乎正在尝试使用螺丝刀 (PHP)。
-
我的目标是输出一个日历。我有一张带预订的桌子,日历是用 php 构建的...
-
另外,我的数据库里只有开始日期和结束日期
-
你的代码让我很困惑。我认为您在array_splice 上犯了一些错误。如果你能做出一些你认为应该如何的模拟输出会有所帮助,这样我就可以确定使用什么方法。
-
$他们有这么多日历应用程序......如果你愿意,我可以推荐一个更简单的版本,可以与你的日期数据库一起使用
标签: php arrays multidimensional-array array-key