php - 在嵌套循环中使用数组耗尽内存

标签 php mysql multidimensional-array out-of-memory nested-loops

这是我遇到的错误。

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/

相关文章:

php - 带有 AND 运算符的正则表达式 mysql

php - 将 WordPress 站点与 git 同步

mysql - 什么是二级 SQL 注入(inject)

php - session ID 和搜索脚本

javascript - jQuery 可排序 : storing values in an multipledimensional array

c++ - 如何用零填充 3D 数组?

PHP - 解析 html 以从另一个 "a"标签内的 "a"标签检索 href

php - 如何从 HTTP GET 请求中获取 JSON 字符串

php - Wordpress Ultimate 成员(member)插件 – 将用户状态设置为等待管理员批准

C - 包含链表的数组