我有以下代码,想要计算我的平均时间 使用date()函数提交spot对象。
$query3 =$pdo->prepare("SELECT * FROM `ks`.`spots` WHERE solved=:solved;");
$query3->bindParam(':solved', $not_solved, PDO::PARAM_INT);
$query3->execute();
$num_of_solved1 = $query3->rowCount();
$results = $query3->fetchAll( PDO::FETCH_ASSOC );
foreach( $results as $row ) {
//$temp_created_at = $row['created_at'];
//$temp_updated_at = $row['updated_at'];
//$time += $row->temp_created_at - $row->temp_updated_at;
$time += $row->created_at - $row->updated_at;
}
$average_time = $time / $num_of_solved1;
答案 0 :(得分:0)
要使用时间进行数学计算,你使用unix时间戳,这基本上是1970年以来的秒数,是一个整数。
foreach( $results as $row ) {
$created = strtotime($row->created_at);
$updated = strtotime($row->updated_at);
$time += $created - $updated;
}
// $time at this point is in seconds
答案 1 :(得分:0)
您可以使用MySQL函数TIMESTAMPDIFF()
进行日期时间减法:
SELECT
*,
TIMESTAMPDIFF(SECOND, `created_at`, `updated_at`) AS `diff`
FROM
`ks`.`spots`
WHERE
solved = :solved
然后在你的循环中,只需加上diff
值:
foreach ($results as $row) {
# ...
$time += $row['diff'];
}