PHP和csv报告计算

时间:2014-02-08 03:44:20

标签: php arrays csv

我有一个csv文件,我想从中生成摘要报告。 csv看起来像这样:

enter image description here

csv在每一行中都有一个活动以及它开始时的相应时间。

我想要生成的摘要必须如下所示:

enter image description here

基本上我需要显示每个活动及其开始和结束的时间

我在PHP中做了如下操作,我差不多完成但是我得到的结果并不是我想要的:

$csvFileName = "The csv path";
$report = array();
$file = fopen($csvFileName, "r");
while (($data = fgetcsv($file, 8000, "\n")) !== FALSE) {
    $num = count($data);
    for ($c = 0; $c < $num; $c++) {
        $t = explode(',', $data[$c]);
        $time = $t[0];
        $activity = $t[1];
    $report[] = array($activity, $time);
    }
}
fclose($file);
//I'm reading the whole file content and copying it into an array.
$summaryReport = array();
$j = 1;
for($i=0; $i<sizeof($report); $i++){
  if($report[$i][0] !== $report[$j][0]){
   array_push($summaryReport,array($report[$i][0],$report[$i][1],$report[$j][1]));
  }
  $j++;
}
echo json_encode($summaryReport);

输出json看起来像这样:

[["Start","10:42","10:59"],["Driving route","11:10","11:50"],["Lunch-Rest Break","11:50","11:57"],["Driving route","11:57","12:03"],["Break","12:11","12:41"],["Driving route","13:05","14:09"],["Waiting","14:14","14:28"]]

我正在寻找的结果是这样的:

[["Start","10:42","10:59"],["Driving route","10:59","11:50"],["Lunch-Rest Break","11:50","11:57"],["Driving route","11:57","12:03"],["Break","12:03","12:41"],["Driving route","12:41","14:09"],["Waiting","14:09","14:28"],["End","14:28"]]

我的编码逻辑不是很好用,有没有人看到我怎样才能做一个简单的循环来做我正在寻找的东西?

提前谢谢。

1 个答案:

答案 0 :(得分:1)

结果可以更轻松地实现。看看我的代码,我摆脱了所有的内部循环,修复了语法错误,并且不需要将整个csv文件存储在内存中:

PHP代码

<?php
$csvFileName = "./test.csv";
$file = fopen($csvFileName, "r");
$summaryReport = array();

$i = 0;
$previous_name = null;
while ($data = fgetcsv($file, 8000)) {
    if ($previous_name !== $data[1])
    {
        $summaryReport[$i] = array($data[1], $data[0]);
        if ($i > 0)
        {
            $summaryReport[$i-1][2] = $data[0];
        }
        $previous_name = $data[1];
        ++$i;
    }
}
fclose($file);

echo json_encode($summaryReport);

测试csv文件

10:41,Start
10:59,Driving
11:29,Driving
11:11,End

输出

[["Start","10:41","10:59"],["Driving","10:59","11:11"],["End","11:11"]]