PHP,相同的数据,相同的计算,不同的结果

时间:2013-01-09 22:43:00

标签: php

我有以下代码。最后,我将评论结果放在服务器上。希望有人可以解释我为什么结果不同,尽管计算是相同的。

<?php 
date_default_timezone_set('UTC'); 

function formatHourToTime($input){ 
    if (strpos($input, '.') !== false){ 
            $array = explode(".",$input); 
    } 
    elseif (strpos($input, ':') !== false){ 
            $array = explode(":",$input); 
    } 
    elseif (strpos($input, ',') !== false){ 
            $array = explode(",",$input); 
    } 
    elseif ($input >= '0' & $input < '24'){ 
            $array = array($input); 
    } 
    else { 
            $time = false; 
            exit(); 
    } 
    $time = $array[0]*3600+$array[1]*60+$array[2]; 
    return $time; 
} 

$matin_d = 0; //midnight timestamp 0.00 
$matin_f = 10800; //ts de 3h00 
$soir_d = 79200; //ts de 22h00 
$soir_f = 82799; //ts de 23h59:59 

function nightwork($start, $end){ 

    if ($start < $matin_f && $end > $soir_d) $totalheures = ($matin_f - $start)/2 + ($end - $soir_d)/2+100000; 
    elseif ($start < $matin_f && $end < $matin_f) $totalheures = ($end - $start)/2+200000; 
    elseif ($start >= $soir_d && $end > $soir_d) $totalheures = ($end - $start)/2+300000; 
    elseif ($start < $matin_f) $totalheures = ($matin_f-$start)/2+400000; 
    elseif ($end>$soir_d) $totalheures = ($end-$soir_d)/2+500000; 
    else $totalheures = 0+600000;  

    return $totalheures; 
} 

$start = formatHourToTime('07:39:00')*1; 

$end = formatHourToTime('08:00:00')*1; 
$shiftnw = nightwork($start, $end); 
if($start >= $soir_d && $end > $soir_f) $bool = 'true'; 
else $bool = 'false'; 
//même code que la fonction nightwork 
    if ($start < $matin_f && $end > $soir_d) $totalheures = ($matin_f - $start)/2 + ($end - $soir_d)/2+100000; 
    elseif ($start < $matin_f && $end < $matin_f) $totalheures = ($end - $start)/2+200000; 
    elseif ($start >= $soir_d && $end > $soir_d) $totalheures = ($end - $start)/2+300000; 
    elseif ($start < $matin_f) $totalheures = ($matin_f-$start)/2+400000; 
    elseif ($end>$soir_d) $totalheures = ($end-$soir_d)/2+500000; 
    else $totalheures = 0+600000;  

echo $start.' '.$end.'<br>'; 
echo $totalheures. ' ' .$shiftnw;  
//$totalheures is calculated following the script
//while $shiftnw is calculated by calling the function having the same lines 
// prints : 
// 27540 28800 
// 600000 300630 
?>

1 个答案:

答案 0 :(得分:1)

看来问题是在nightwork()函数中你无法访问这些变量:

$matin_d = 0; //midnight timestamp 0.00 
$matin_f = 10800; //ts de 3h00 
$soir_d = 79200; //ts de 22h00 
$soir_f = 82799; //ts de 23h59:59

尽管您可以在脚本末尾计算的全局范围内访问它们。

您还需要将这些值放在函数中,将它们作为参数传递给函数,在函数内部将它们声明为global,或者将它们定义为它们可用于所有区域的常量你的脚本,无论范围如何。

相关问题