状态持续时间,以每天百分比表示

时间:2014-09-09 11:18:23

标签: php algorithm date

我需要帮助算法。 一般来说,我有这样的数组:

**Status** (3 options available), **Start** (in timestamp format), **Duration** (in seconds)
**Status**, **Start**, **Duration**
**Status**, **Start**, **Duration**
and so on.........

持续时间可能是几分钟到几天。我希望以某种方式计算每个状态消耗多少百分比。

date1 | %of status1 | %of status2 | %of status3
date2 | %of status1 | %of status2 | %of status3

需要最终输出

2014-09-08 | 73 | 22 | 5
2014-09-07 | 100 | 0 | 0
2014-09-06 | 46 | 34 | 20

我没有任何代码可以展示,因为我无法弄清楚算法,如何实现。任何帮助将不胜感激

我的输入是CSV文件,我将用PHP编程,但是可以使用任何语言的帮助。

1 个答案:

答案 0 :(得分:0)

如果有人有兴趣 - 我设法创建算法

<?php
//prepare my $csv array as in question

$final = array();
foreach($csv as $key => $val){

    //start + duration, is still the same day?
    if (date('Y-m-d', $csv[$key]["start"]) == date('Y-m-d', $csv[$key]["start"]+$csv[$key]["duration"])) {
        $final[date('Y-m-d', $csv[$key]["start"])][$csv[$key]["status"]] += $csv[$key]["duration"];
    }
    //we have to split duration of status over days
    else{
        //timestamp of upcomming midnight
        $midnight = mktime(0, 0, 0, date('m', $csv[$key]["start"]), date('d', $csv[$key]["start"])+1);
        $tillMidnightDuration = $midnight - $csv[$key]["start"];
        $afterMidnightDuration = $csv[$key]["duration"]- $tillMidnightDuration;

        $final[date('Y-m-d', $csv[$key]["start"])][$csv[$key]["status"]] += $tillMidnightDuration;

        $day=0;
        //handle after midnight duration
        while($afterMidnightDuration>0){
            //after midnight- next day
            $day++;
            // 86400 is one full day in seconds
            if($afterMidnightDuration > $secondsPerDay){
                $final[date('Y-m-d', mktime(0, 0, 0, date('m', $csv[$key]["start"]), date('d', $csv[$key]["start"])+$day))][$csv[$key]["status"]] += $secondsPerDay;
                $afterMidnightDuration = $afterMidnightDuration - $secondsPerDay;
            }
            // not full day
            else{
                $final[date('Y-m-d', mktime(0, 0, 0, date('m', $csv[$key]["start"]), date('d', $csv[$key]["start"])+$day))][$csv[$key]["status"]] += $afterMidnightDuration;
                $afterMidnightDuration = 0;
            }
        }
    }
}
?>

现在在$ final数组中,我将每天作为关键字,持续时间以秒为单位