iDo*_*ler 2 php mysql out-of-memory nested-loops multidimensional-array
这是我得到的错误.
致命错误:允许的内存大小耗尽.
我正在获取包含日期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"));
}
}
Run Code Online (Sandbox Code Playgroud)
rob*_*bmj 10
看起来你做了一个无限循环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"));
}
Run Code Online (Sandbox Code Playgroud)
将1日期添加到当前值$from
while ($from <= $till){
$nonAvailable[] = $from;
// add 1 day to $from
$from = date('Y-m-d', strtotime($from, "+1 days"));
}
Run Code Online (Sandbox Code Playgroud)
仍然可以做出一些改进:
reservation数组中,我们只从表中检索所需的列.
integers而不是strings.
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();
Run Code Online (Sandbox Code Playgroud)
这种算法可能会更有效率.例如,您是否需要每天保留一些详尽的清单?如果没有,那么只需要开始日期和结束日期即可.
1 给定足够的时间和内存,循环将退出,因为strtotime("+1 days")最终将返回大于的值$till.