我有一个包含日期的2列的mySQL表。while循环将每个变量放入一个变量:$start_date和$end_date,计算它们之间的时间,并通过使用diff()将它们放入一个新变量$since_start中;据我所理解,使用diff()将生成一个DateInterval类。
现在,我想在'while‘循环中构建一个和,并将它存储在$total_received变量中。在搜索完网络和堆栈溢出之后,我最后一次尝试的是
$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 ";
非常感谢您提前!
发布于 2017-08-03 16:33:06
问题是:
$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 ";
https://stackoverflow.com/questions/45488989
复制相似问题