Last active
August 29, 2015 13:57
-
-
Save KaduNovoK/9597673 to your computer and use it in GitHub Desktop.
Sum the elements of a field in a array with predefined fields
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 | |
// Log of players result | |
$dataArray = array( | |
array('player' => 'John', 'day' => '1', 'points' => 230), | |
array('player' => 'Hans', 'day' => '1', 'points' => 300), | |
array('player' => 'Karl', 'day' => '1', 'points' => 200), | |
array('player' => 'John', 'day' => '1', 'points' => 250), | |
array('player' => 'Hans', 'day' => '1', 'points' => 300), | |
array('player' => 'Karl', 'day' => '1', 'points' => 190), | |
array('player' => 'John', 'day' => '2', 'points' => 200), | |
array('player' => 'Hans', 'day' => '2', 'points' => 330), | |
array('player' => 'Karl', 'day' => '2', 'points' => 250), | |
array('player' => 'John', 'day' => '2', 'points' => 300), | |
array('player' => 'Hans', 'day' => '2', 'points' => 200), | |
array('player' => 'Karl', 'day' => '3', 'points' => 220), | |
); | |
// Objective: sum the points of the each players in each day | |
$newDataArray = array(); | |
foreach($dataArray as $node) { | |
$hashContent = array( | |
$node['player'], | |
// $node['day'], // Uncomment to see the new result | |
); | |
$hash = hash('md5', implode('--', $hashContent)); | |
if (isset($newDataArray[$hash])) { | |
$newDataArray[$hash]['points'] += $node['points']; | |
} else { | |
$newDataArray[$hash] = $node; | |
} | |
} | |
var_dump($newDataArray); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment