【问题标题】:how to add time/duration from database using php如何使用 php 从数据库中添加时间/持续时间
【发布时间】:2013-03-01 07:41:57
【问题描述】:

我有这个来自数据库的数据。

+----+------------+----------+
| id |     date time        |  duration |
+----+------------+----------+-----------
| 3  | 2012-12-20  09:28:53 |     ?     |
| 1  | 2012-12-20  19:44:10 |    ?      |
| 2  | 2012-12-23  16:25:15 |           |
| 4  | 2012-12-23  18:26:16 |           |
| 4  | 2012-12-24  08:01:27 |           |
| 5  | 2012-12-29  20:57:33 |           | 
| 5  | 2012-12-29  20:57:33 |           | 
+----+------------+----------+------------
  • id #1 的持续时间应等于日期 id #2 - id #1
  • id #2 的持续时间应等于日期 id #3 - id #2

如果id相同,则会添加。

对不起,这只是我的想法,在 php 中仍然很新,所以我不知道如何开始。 任何帮助表示赞赏。 谢谢

已编辑按日期排序。第 1 条记录的持续时间或总时间 = 第 2 条记录 - 第 1 条记录

【问题讨论】:

  • 尝试将日期转换为内部格式(您会看到它是 Unix 时间戳或类似的东西)。在这种格式中,您只需减去两个日期/时间,就可以得到它们之间的差异(以秒为单位)。
  • 我已经使用 strtotime 进行转换,但我的问题是因为这是从数据库中获取的,如何将它放在 id 1、id 2 等的持续时间列中。请指导我,也许它是嵌套循环,但我仍然不知道该怎么做。再次感谢
  • 好吧,一旦你确实有这样的时间,你只需将当前减去前一个,然后将它们放入表中的相应位置。是的,您需要遍历表,并按行进行。
  • 我不明白你的要求。您想更改 id#1、id#2 的持续时间值还是什么?
  • 我只有查询中的表(fetch_array)但没有持续时间,因为我不知道如何放置它。我还是个循环新手,所以我真的不知道如何表达。

标签: php database datetime add


【解决方案1】:

如果我理解正确的话,有一个东西叫做id=3,它从“2012-12-20 09:28:53”开始,然后在“2012-12-20 19:44:10”结束,并且在同一秒钟内,id=3 开始了,你想知道这一切会持续多久?

我会对所有记录进行循环,但我会从结束开始(在 SQL 中:...ORDER BY date_time DESC),假设最后一个结束(即id=5,开始于 2012 年 12 月 29 日 20 日: 57:33)现在,然后我将持续时间计算为日期的减法(开始和结束),然后我会将事件开始作为前一个事件的结束,依此类推。

一个例子(未测试):

$end=now();
$dbh=new PDO(...); // here you need to connect to your db, see manual
while($record=$dbh->query('SELECT id, datetime FROM table_name ORDER BY datetime DESC')->fetchObject()){
  $start=$record->datetime;
  echo $duration=$end-$start; // convert $end and $start to timestamps, if necessary
  $end=$start; // here I say that next (in sense of loop, in fact it is previous) record will end at the moment where this record started
}

这并不总和,因为我不知道你将如何存储你的数据,但我认为你会用这个来管理。

已编辑

一开始我定义了一个数组:

$durations=array(); // this will hold durations
$ids=array();  // this will hold `id`-s
$last_id=-1; // the value that is not existent

然后代码如下,而不是echo我放这个:

$duration=$end-$start;
if($last->id==$record->id){ // is this the same record as before?
  $durations[count($durations)-1]->duration+=$duration; // if yes, add to previous value
  }
else { // a new id
  $durations[]=$duration; // add new duration to array of durations
  $ids[]=$record->id; // add new id to array of ids
  $last_id=$record->id; // update $last_id 
  }

然后$end=$start 如上所述。

简单地查看所有持续时间和 ID

for($i=0;$i<count($durations);$i++){
  echo 'id='.$ids[$i].', duration='.$durations[$i].'<br />';
  }

请注意,这些表格的顺序是相反的。

【讨论】:

  • 这实际上是我的问题。我不知道如何获取持续时间的数据。我怎样才能将以前的时间减去以后的时间。我不确定是否需要在数组中制作。我还是这个 php 的新手。
猜你喜欢
  • 1970-01-01
  • 2016-02-23
  • 2015-08-31
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 2011-01-25
相关资源
最近更新 更多