如何使用php从数据库添加时间/持续时间

时间:2013-03-01 07:41:58

标签: php database datetime add

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

+----+------------+----------+
| 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
  • 身份#2的持续时间应等于日期ID #3 - id#2

如果id相同,则会添加。

抱歉,这只是我的想法,在php中还是很新的,所以我不知道如何开始。 任何帮助表示赞赏。 感谢

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

1 个答案:

答案 0 :(得分:0)

如果我理解正确,有一些名为id=3并且从“2012-12-20 09:28:53”开始,则结束于“2012-12-20 19:44:10 “并且在同一秒钟id=3开始了,你想知道一切都持续多久?

我会为所有记录做一个循环,但我会从结束开始(在SQL中:...ORDER BY date_time DESC),假设最后一个结尾(即{2012}开始的id=5 -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
}

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

EDITED

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

$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 />';
  }

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