Skip to content

Instantly share code, notes, and snippets.

@kiang
Created October 28, 2014 19:30
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kiang/5fc906e31706aee9172f to your computer and use it in GitHub Desktop.
<?php
$rFh = fopen(__DIR__ . '/report1.csv', 'w');
fputcsv($rFh, array('代碼', '<=97', '>97', '+/-', '差異數', '變動比例'));
$stack = array();
foreach (glob(dirname(__DIR__) . '/goods/good_in/*-4code.csv') AS $csvFile) {
$p = pathinfo($csvFile);
/*
* Array
(
[0] => 100
[1] => 1
[2] => 4code
)
*/
$f = explode('-', $p['filename']);
$fh = fopen($csvFile, 'r');
fgetcsv($fh, 512);
while ($line = fgetcsv($fh, 2048)) {
/*
* Array
(
[0] => 貨品分類
[1] => 國家
[2] => 重量
[3] => 重量單位
[4] => 價值
)
*/
if ($line[1] === '合計' && $f[0] < 103) {
if (!isset($stack[$line[0]])) {
$stack[$line[0]] = array();
for ($i = 92; $i < 103; $i++) {
$stack[$line[0]][$i] = 0;
}
}
$stack[$line[0]][$f[0]] += $line[2];
}
}
fclose($fh);
}
$result = array();
foreach ($stack AS $code => $years) {
$result[$code] = array(
'<=97' => array(
'total' => 0,
'count' => 0,
'avg' => 0,
),
'>97' => array(
'total' => 0,
'count' => 0,
'avg' => 0,
),
);
foreach ($years AS $year => $weight) {
if ($weight > 0) {
if ($year > 97) {
$result[$code]['>97']['count'] ++;
$result[$code]['>97']['total'] += $weight;
} else {
$result[$code]['<=97']['count'] ++;
$result[$code]['<=97']['total'] += $weight;
}
}
}
foreach ($result[$code] AS $k => $v) {
if ($result[$code][$k]['count'] > 0) {
$result[$code][$k]['avg'] = round($result[$code][$k]['total'] / $result[$code][$k]['count']);
}
}
$diff = abs($result[$code]['<=97']['avg'] - $result[$code]['>97']['avg']);
fputcsv($rFh, array(
$code . '-',
$result[$code]['<=97']['avg'],
$result[$code]['>97']['avg'],
$result[$code]['>97']['avg'] >= $result[$code]['<=97']['avg'] ? '+' : '-',
$diff,
$result[$code]['<=97']['avg'] > 0 ? round($diff / $result[$code]['<=97']['avg'], 2) : 0,
));
}
fclose($rFh);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment