2017-08-03 95 views
0

我有一个包含日期的2列的mySQL表。 while循环将每个变量放入一个变量中:$ start_date和$ end_date,计算它们之间的时间,并通过使用diff()将它们放入一个新变量$ since_start中;据我了解在DateInterval类中使用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 "; 

非常感谢您提前!

回答

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 ";