Skip to content

Instantly share code, notes, and snippets.

@ecelis
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ecelis/318fb5edfd8f3b2272dd to your computer and use it in GitHub Desktop.
Save ecelis/318fb5edfd8f3b2272dd to your computer and use it in GitHub Desktop.
Aggregate data in PHP
<form action="process.php" method="post">
<textarea name="myinput" id="myinput" cols="12" rows="6"></textarea>
<input type="submit" value="send">
</form>
<?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