在循环内递增DateInterval

时间:2017-08-03 15:46:26

标签: php mysql loops while-loop dateinterval

我有一个mySQL表,其中包含2个包含日期的列。 while循环将每个变量放入一个变量:$ start_date和$ end_date,计算它们之间的时间,并使用diff()将它放入一个新变量$ since_start;据我所知,使用diff()会导致DateInterval类。

现在我想在'while'循环期间构建一个总和并将其存储在$ total_received变量中。在搜索网络和stackoverflow之后,我尝试的最后一件事是

$total_received->add(new DateInterval($since_start));

但这似乎是错误的,因为我没有得到任何输出。我不知道我做错了什么,但我不知道我在用这条线做什么,说实话,不知道在哪里看。我希望我能找到谷歌的答案,因为它更快,但我不能。我希望你能帮忙!

这是完整的循环,之前定义了$ total_received变量并在之后发布。

//Set variable for lifetime received total
$total_received = 0;

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo 
          $row["id"] ." "
        . $row["donor"]." ";
        $start_date = new DateTime($row["start"]);
        $end_date = new DateTime($row["end"]);
        $since_start =  $start_date->diff($end_date);
        $total_received->add(new DateInterval($since_start));
        echo $since_start->format('%h')." Hours ".$since_start->format('%i')." Minutes "
        . $row["subject"] ." " 
        . $row["complete"] ."<br>";
    }
} else {
    echo "No lifetime received yet";
}

echo $total_received->format('%h')." Hours ".$total_received->format('%i')." Minutes ";

非常感谢你!

1 个答案:

答案 0 :(得分:0)

问题在于:

  • $total_received = 0将该变量初始化为一个数字,该数字没有您稍后使用的add方法。
  • $since_start已经是DateInterval,因此执行new DateInterval($since_start)没有多大意义,并会触发错误

您无法一起添加日期间隔,只能将日期间隔添加到日期/时间。因此,使用一些参考日期/时间,并添加每个间隔。最后,您将参考日期/时间的差异与结果日期/时间一起获得最终间隔:

// Create the "interval" as a start/end reference date
$ref_start = new DateTime("00:00");
$ref_end = clone $ref_start;

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo 
          $row["id"] ." "
        . $row["donor"]." ";
        $start_date = new DateTime($row["start"]);
        $end_date = new DateTime($row["end"]);
        $since_start =  $start_date->diff($end_date);
        // Move the end date/time of the reference period
        $ref_end->add($since_start);
        echo $since_start->format('%h')." Hours ".$since_start->format('%i')." Minutes "
        . $row["subject"] ." " 
        . $row["complete"] ."<br>";
    }
} else {
    echo "No lifetime received yet";
}
// Only now convert the reference period to an interval
$total_received = $ref_start->diff($ref_end);

echo $total_received->format('%h')." Hours ".$total_received->format('%i')." Minutes ";