I have an array that I get back from an SQL query and it looks like this when I do print_r
:
Array(
[0] => Array(
[id] => 1,
[protein] => 20,
[carbs] => 64,
[date] => 2014-02-24
),
[1] => Array(
[protein] => 1,
[carbs] => 12,
[score2] => 8,
[date] => 2014-02-24
),
[2] => Array(
[id] => 1,
[protein] => 47,
[carbs] => 84,
[date] => 2014-02-25
)
)
Now what I would like to do to this array is add up the carbs and protein values for each particular date. So take day 2014-02-24
I would like it for the carb
and protein
values to equal to 21
and 76
. So far I can access each individual value in a foreach loop but I am not sure how I can save these to a specific date. Here is the loop I am using:
foreach ($res as $row) {
echo $row['protein'] . "<br />" . $row['carbs'] . "<br />" . $row['date'] . "<br />";
}
So obviously this doesn't give me the results I want but I am not sure how to group the information by a certain date, can someone explain how I can do this?
You need to loop over the array and add the totals for each carbs and protein to a variable or array representing each date to get the total for that date:
$grouped = array();
foreach($res as $row) {
if(!array_key_exists($row['date'], $grouped)) // create array key if it doesnt exist
$grouped[$row['date']] = array('protein' => 0, 'carbs' => 0);
$grouped[$row['date']]['protein'] += $row['protein']; // sum for each date
$grouped[$row['date']]['carbs'] += $row['carbs'];
}
print_r($grouped);
Example output:
Array(
[2014-02-24] => Array(
[protein] => 21
[carbs] => 76
)
[2014-02-25] => Array(
[protein] => 47
[carbs] => 84
)
)