这是我遇到的错误。
Fatal Error: Allowed memory size exhausted.
我正在获取包含日期 from
和日期 till
的数组。我正在尝试获取介于两者之间的所有日期并将它们添加到新数组中。显然,嵌套循环和多数组令人筋疲力尽。
我需要一种不那么费力的方法来获取所有日期。
这是我的代码:
$query = "SELECT *
FROM reservate
ORDER BY from";
$result = $connect->query($query);
$reservations = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$reservations[] = $row;
}
}
$connect->close();
//AVAILABILITY CHECK
$nonAvailable = array();
foreach($reservations as $reservation){
$from = $reservation['from'];
$till = $reservation['till'];
while($from <= $till){
$nonAvailable[] = $from;
$from = date('Y-m-d', strtotime("+1 days"));
}
}
最佳答案
看起来你做了一个无限循环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
数组,我们只检索我们需要的列 从表中。 - >
比较
整数
而不是字符串
。 - >
手动将
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();
很可能可以使该算法更加高效。例如,您是否需要一份包含每天保留内容的详尽 list ?如果不是,则只需开始日期和结束日期就足够了。
1 如果有足够的时间和内存,循环将退出,因为 strtotime("+1 days")
最终会返回一个大于 $till
的值>.
关于php - 在嵌套循环中使用数组耗尽内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29233011/