我正在制作一个PHP时间转换器,可以将时间从天,小时,分钟转换为秒。我需要使用argv
和switch语句。然而,它并没有真正转换相同参数的倍数。例如:input:php time.php 2m 2m
输出:120 Seconds
。应该是240秒。
我试过使用count
。这是可行的,但前提是你们有相同的论点。当你有小时,分钟,天,秒。在一起是行不通的。这是我当前的代码,它可以使用每个参数
<?php
//variables
$time = implode(" ", $argv);
$timearray = (explode(" ", $time));
$timeday = 0;
$timehour = 0;
$timemin = 0;
$timesec = 0;
//loop
foreach ($timearray as $time) {
$letter = substr($time, -1);
$aantal = substr($time, 0, -1);
//switch
switch ($letter) {
case "d":
$timeday = $aantal * 86400;
break;
case "u":
$timehour = $aantal * 3600;
break;
case "m":
$timemin = $aantal * 60;
break;
case "s":
$timesec = $aantal * 1;
break;
}
$total = ($timeday + $timehour + $timemin + $timesec);
}
echo $total . " Seconds" . PHP_EOL;
我不知道怎么修理它。
您可以将其简化很多:
<?php
array_shift($argv);
$total = 0;
foreach ($argv as $time) {
$letter = substr($time, -1);
$aantal = substr($time, 0, -1);
switch ($letter) {
case "d":
$total += $aantal * 86400;
break;
case "u":
$total += $aantal * 3600;
break;
case "m":
$total += $aantal * 60;
break;
case "s":
$total += $aantal * 1;
break;
}
}
echo $total . " Seconds" . PHP_EOL;