0

我在数组中有以下数据结构,我正在尝试计算总持续时间:

 $elements = array(
                        'elementfrom-work' => "09:00",
                        'elementto-work' => "17:00",
                        'elementdays-work' => "5",

                        'elementfrom-karate' => "18:00",
                        'elementto-karate' => "20:00",
                        'elementdays-karate' => "3",

                        'elementfrom-stamp' => "21:00",
                        'elementto-stamp' => "22:00",
                        //it doest have the default days 'elementdays-stamp' set
                         //so it will take the default 7
                        'element-simple1' => "4", //it will take the default 7
                        'element-simple2' => "8",  //it will take the default 7
                        'element-simple3' => "1",
                        'elementdays-simple3' => "1", //day is set
    );

我已经设法做到了,但是我的代码很混乱,对于每个项目,它都会获取子字符串并运行另一个 for 循环以检查是否存在其他不简单的元素(例如天)。

我正在尝试计算每个项目的总持续时间,例如结果是:

Work:40
Karate:6
Stamp:7
Simple1=28
Simple2=56
Simple3=1

total duration:138

这可以在没有两个 for 循环的情况下完成吗?如何?如果不可能,您将如何计算。

4

2 回答 2

1

看起来您知道日期项目的预期名称...检查它是否存在而不是循环,迭代数组键,当您到达“elementfrom-work”时,您可以检查数组是否有键“elementdays-work”的重复以 N 级复杂度搜索此项目...

于 2013-03-07T23:54:32.837 回答
1

我实际上发现这个问题很有趣,因此您可以执行以下操作:

$elements[] = array(
    'elementfrom-work' => "09:00",
    'elementto-work' => "17:00",
    'elementdays-work' => "7",

    'elementfrom-karate' => "18:00",
    'elementto-karate' => "20:00",
    'elementdays-karate' => "3",

    'elementfrom-stamp' => "21:00",
    'elementto-stamp' => "22:00",

    'a' => "21:00",
    'b' => "22:00"
);

并使用这两个功能:

function negative($x)
{
    if($x < 0)
    {
        return -$x;
    }
    return $x;
}

function isTime($string)
{
    $split = explode(":", $string);

    if(isset($split[1]))
    {
        return true;
    }
    return false;
}

foreach($elements as $key => $val)
{
    $total = 0;
    $temp = 0;
    $i = 0;
    foreach($val as $innerKey => $time)
    {
        $isTime = isTime($time);
        $split = explode(":", $time);
        $h = $split[0];

        switch($i)
        {
            case 0:
                $temp -= $h;
                break;

            case 1:
                $temp += $h;
                break;

            case 2:
                if($isTime)
                {
                    $mult = $temp *= 7;
                    $unsigned = negative($mult);
                    $total += $unsigned;
                    $temp = 0;
                    $temp -= $h;
                    $i = 0;
                    break;
                }
                $mult = $temp *= $h;
                $unsigned = negative($mult);
                $total += $unsigned;
                $temp = 0;
                $i = -1;
                break;

            default:
                 break;
        }
        $i++;
    }
    echo $total;
}

你对进位的想法有点时髦,但类似的东西应该可行。

于 2013-03-08T02:02:04.897 回答