2012-02-02 123 views
1

我有一个while循环中下列变量:在while循环做一个计算

$row['To']; 
    $row['From']; 

那些表示时间,例如:

$row['To'] ="10:00:00"; 
$row['From'] = "08:00:00"; 

在正常计算我将执行以下操作得到的差异小时:

$result = (strtotime($row['To']) - strtotime($row['From'])); 
    $hours  = floor($result/60/60); 
    $minutes = round(($result - ($hours * 60 * 60))/60); 

问题是,现在我必须做一个while循环,$ row ['to'] a nd $ row ['From']必须计算循环规定的所有时间...但我无法得到它的工作。这是我试过的:

function calculateHours($project, $worker, $year, $month) { 
if($project) { 
$q='SELECT * FROM project_timeline WHERE ID="'.$project.'" AND Year(Date) = "'.$year.'" AND Month(Date) = "'.$month.'" AND WorkerID="'.$worker.'"'; 
}else{ 
$q='SELECT * FROM project_timeline WHERE Year(Date) = "'.$year.'" AND Month(Date) = "'.$month.'" AND WorkerID="'.$worker.'"'; 
} 
$r=mysql_query($q) or die(mysql_error()); 
    while($row = mysql_fetch_array($r)) { 
    $result .= (strtotime($row['To']) - strtotime($row['From'])); 
    } 
    $hours  = floor($result/60/60); 
    $minutes = round(($result - ($hours * 60 * 60))/60); 
return $hours.' hour(s) and '.$minutes.' minutes'; 
} 

我该如何解决它? 谢谢

回答

1

为什么你使用.=计算PHP中的数字(时间)这是字符串加法,用于添加数字使用+=

而只是聪明码 - 把$result = 0;在功能

PS的开始。此外,而不是地板时,尽量使用% -

$result  = round($result/60); 
$minutes = $result % 60; 
$hours  = ($result - $minutes)/60; 
0

使用return像你while()循环内将要终止在第一次迭代循环,永远只能产生结果数据的第一行,你已经取来自数据库。

+0

存在而没有回报 - 这是正确的 – SergeS 2012-02-02 19:56:31

+0

人物啊......坏压痕打击一次。 – 2012-02-02 19:57:02

0

我会用DateTime类这样的:

// other function code here... 

$from = new DateTime($row['From']); 
$to = new DateTime($row['To']); 
$diff = $from->diff($to); 

return $diff->format('%h hour(s) and %i minutes'); 
+0

和while循环在哪里? – SergeS 2012-02-02 19:57:07

+0

@SergeS:我误解了他想要做的事情。 'DateInterval'对此不起作用,因为你不能指定总面值并获得小时/分钟/秒(尽管这对于未来的PHP版本来说是一个很好的补充!)。 – FtDRbwLXw6 2012-02-02 20:25:49

+1

你总是可以做到这一点 - 首先从开始,以及任何下一个不同的添加到第一个时间(所以第一个从 - 将会使计算差异) – SergeS 2012-02-03 07:46:24