将数据转换为数组,并根据过滤器查找计数

时间:2014-08-12 02:57:58

标签: php arrays counting

我有数据存储在文本文件中(这是一项要求),我已经变成了一个数组...... 现在我正在尝试根据2个变量$ Start_Date& $ END_DATE ...然后只显示旁边有计数的唯一值。

Stats.txt

08/02/14 | Red | Wood
08/03/14 | Red | Steel
08/04/14 | Blue | Wood
08/05/14 | Red | Steel
08/05/14 | Red | Wood
08/05/14 | Red | Steel
08/05/14 | Blue | Steel
08/06/14 | Blue | Wood

到目前为止我所拥有的:

  $logfile = "stats.txt";
  $Start_Date = 08/04/14;
  $End_Date = 08/05/14;

  if (file_exists($logfile)) {

        $handle = fopen($logfile, "r");
        $log = fread($handle, filesize($logfile));
        fclose($handle);

  } else {
        die ("The log file doesn't exist!");
  }

  // Seperate each logline

  $log = explode("\n", trim($log));

  // Seperate each part in each logline
  for ($i = 0; $i < count($log); $i++) {
        $log[$i] = trim($log[$i]);
        $log[$i] = explode('|', $log[$i]);
  }

所需结果:(基于$ Start_Date = 08/04/14和$ End_Date = 08/05/14)

<h2>Date Count:</h2>
08/04/14 - 1
08/05/14 - 4

<h2>Color Count:</h2>
Red - 3
Blue - 2

<h2>Material Count:</h2>
Wood - 2
Steel - 3

1 个答案:

答案 0 :(得分:0)

编写像这样的代码

$log = "08/02/14 | Red | Wood
08/03/14 | Red | Steel
08/04/14 | Blue | Wood
08/05/14 | Red | Steel
08/05/14 | Red | Wood
08/05/14 | Red | Steel
08/05/14 | Blue | Steel
08/06/14 | Blue | Wood";

$log = explode("\n", trim($log));   
// Seperate each part in each logline
$dateFreq = array();
$colorFreq = array();
$MaterialFreq = array();
foreach ($log as $line) {
    $lineArr = explode("|", $line);
    $date = trim($lineArr[0]);
    $color = trim($lineArr[1]);
    $material = trim($lineArr[2]);
    if ($date >= '08/04/14' && $date <= '08/05/14') {  
        if (isset($dateFreq[$date])) {
            $dateFreq[$date] = $dateFreq[$date] + 1;
        } else {
            $dateFreq[$date] = 1;
        }
        if (isset($colorFreq[$color])) {
            $colorFreq[$color] = $colorFreq[$color] + 1;
        } else {
            $colorFreq[$color] = 1;
        }
        if (isset($MaterialFreq[$material])) {
            $MaterialFreq[$material] = $MaterialFreq[$material] + 1;
        } else {
            $MaterialFreq[$material] = 1;
        }
    }
}
echo "<h2>Date Count:</h2>\n";
foreach ($dateFreq as $date => $freq) {
    echo $date, " - ", $freq, "\n";
}

echo "<h2>Color Count:</h2>\n";
foreach ($colorFreq as $color => $freq) {
    echo $color, " - ", $freq, "\n";
}

echo "<h2>Material Count:</h2>\n";
foreach ($MaterialFreq as $material => $freq) {
    echo $material, " - ", $freq, "\n";
}