我有一个我要导入的Excel工作表,但我希望将一些数据转换为分钟。虽然格式从5h 5m 6.64s
到6.64s
不等但我怎样才能将其转换为PHP中的几分钟? (我确信DateTime::createFromFormat()
不会工作,因为它的范围是0到59.)
在PHP应用程序中操作和绘图或将其从PHP类转换为某个时间对象更容易转换为分钟是一种更简单的格式吗?
请记住,数据必须格式化,然后导入MySQL服务器,然后读回PHP应用程序以进行统计。我也使用cakePHP框架来构建应用程序。感谢您的任何反馈。
答案 0 :(得分:2)
如果所有时间都有像h m s这样的格式(其中任何一个都是可选的),我认为提取数字一点也不困难。这可以通过简单的正则表达式完成:
/(([0-9]{1,2})h)?(([0-9]{1,2})m)?(([0-9]{1,2}\.[0-9]{0,2})s)?/
然后你可以简单地将这些数字放在PHP的DateTime
对象中。并将其转换为存储在数据库中的格式。
答案 1 :(得分:1)
如果字符串的不同部分始终用空格分隔,则可以使用:
$timeParts = explode(' ', $timestring); //Separates your time string in parts
//To sum these parts into a total number of minutes:
//First make an array with all multiplication factors to go from part of string to a number of minutes
$factors = array(1/60, 1, 60, 60*24); //Last value is for days, which are probably not necessary.
//Iterate through the $timeParts array
$minutes = 0; //Create $minutes variable, so we can add minutes to it for each string part
while($part = array_pop($timeParts)) { //Process each part of the string, starting from the end (because seconds will always be there even if minutes aren't)
$part = floatval($part); //I guess your numbers will technically be strings, so we need to convert them to floats (because the seconds need to be floats). Also, this function should strip off any letters appended to your numbers.
$factor = array_shift($factors); //Take the first part of the $factors array (because in that array the seconds are first, then minutes and so on)
$minutes += ($part * $factor); //Multiply the string part by its matching factor and add the result to the $minutes variable.
}
我没有对此进行过测试,因此您需要自行调试。