php嵌套循环太慢,php - 内存在嵌套循环中使用数组耗尽 - 堆栈内存溢出

看起来你做了一个无限循环1 。

// if $till is in the future, this is an infinite loop

while($from <= $till){

// appending the same value of $from on each iteration

$nonAvailable[] = $from;

// as $from never changes value

$from = date('Y-m-d', strtotime("+1 days"));

}

将1天添加到$from的当前值

while ($from <= $till){

$nonAvailable[] = $from;

// add 1 day to $from

$from = date('Y-m-d', strtotime($from, "+1 days"));

}

仍然可以做出一些改进:

在以下示例中,整个表不会复制到reservation数组,我们只从表中检索所需的列。

比较integers而不是strings 。

$from手动添加1天到$from而不是依靠strtotime来做。

$query = "SELECT from, till

FROM reservate

ORDER BY from";

$result = $connect->query($query);

$nonAvailable = array();

if ($result->num_rows > 0) {

while ($row = $result->fetch_assoc()) {

$from = strtotime($row['from']);

$till = strtotime($row['till']);

while ($from <= $till) {

$nonAvailable[] = date('Y-m-d', $from);

$from += 60*60*24;

}

}

}

$connect->close();

这种算法很可能会变得更有效率。 例如,您是否需要每天保留一些详尽的清单? 如果没有,那么只需要开始日期和结束日期即可。

1 给定足够的时间和内存,循环将退出,因为strtotime("+1 days")最终会返回大于$till的值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值