Last active
August 29, 2015 14:13
-
-
Save ecelis/318fb5edfd8f3b2272dd to your computer and use it in GitHub Desktop.
Aggregate data in PHP
This file contains hidden or 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
<form action="process.php" method="post"> | |
<textarea name="myinput" id="myinput" cols="12" rows="6"></textarea> | |
<input type="submit" value="send"> | |
</form> |
This file contains hidden or 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 | |
/* This code takes input like this: | |
aaf341:40 | |
bb33bs:10 | |
98jjnw:10 | |
000000:20 | |
aaf341:40 | |
and outputs this | |
aaf341:80 | |
bb33bs:10 | |
98jjnw:10 | |
000000:20 | |
*/ | |
$data = explode("\n", $_POST['myinput']); | |
$group = array(); | |
foreach($data as $item) { | |
// explode into key -> value | |
$kv = explode(":",$item); | |
if(array_key_exists($kv[0], $group)) { | |
// If the key item already exists add it | |
$group[$kv[0]] += floatval($kv[1]); | |
} else { | |
$group[$kv[0]] = floatval($kv[1]); | |
} | |
} | |
foreach($group as $product => $totals) { | |
echo $product.":".$totals."<br>"; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment