Created
March 11, 2019 23:13
-
-
Save elifiner/1b9b78e28d7316c1aa8b7e8388175dcc to your computer and use it in GitHub Desktop.
Compute simple pivot table of a CSV file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (count($argv) < 4) { | |
echo " | |
Usage: php pivot.php <file> <column>[,<column>] <column>:<func> | |
Examples: | |
php pivot.php data.csv Type sum:Amount | |
php pivot.php data.csv Type,Description sum:Amount | |
"; | |
exit(1); | |
} | |
[$script, $file, $columns, $func] = $argv; | |
$in = fopen($file, 'r'); | |
$out = fopen('php://stdout', 'w'); | |
$columns = explode(',', $columns); | |
[$func, $func_column] = explode(':', $func); | |
$headers = fgetcsv($in); | |
$pivot = []; | |
while (true) { | |
$data = fgetcsv($in); | |
if ($data === false) break; | |
$data = array_combine($headers, $data); | |
$key = serialize(array_intersect_key($data, array_flip($columns))); | |
$pivot[$key][] = $data[$func_column]; | |
} | |
$header = false; | |
foreach ($pivot as $key => $values) { | |
if (! $header) { | |
fputcsv($out, array_merge(array_keys(unserialize($key)), [$func])); | |
$header = true; | |
} | |
// todo: support other functions | |
$sum = array_sum($values); | |
if (abs($sum) < 0.05) continue; | |
fputcsv($out, array_merge(unserialize($key), [$sum])); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment