Reputation: 43
I have an array with data that i would want to group, example below:
[
{
"date": "04-06-2016",
"emmission": 3450
},
{
"date": "04-06-2016",
"emmission": 91
},
{
"date": "09-02-2016",
"emmission": 10
},
{
"date": "04-06-2016",
"emmission": 7
},
{
"date": "19-04-2016",
"emmission": 28
},
{
"date": "08-05-2015",
"emmission": 7
},
{
"date": "04-06-2016",
"emmission": 15
},
{
"date": "04-06-2016",
"emmission": 109
}
]
What i am trying to do is group them together by date and calculate the emmission value(sum by date);
thus the duplicated array like: { "date": "04-06-2016", "emmission": 3450 }
should only exists once and the emmission should be sum, i have tried almost everything from array_unique to array_search but still no luck.
Thanks
What i have now
public function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
// $temp_array[$i]['emmission'] += $array[$i]['emmission'];
}
$i++;
}
return $temp_array;
}
$this->unique_multidim_array($history, 'date');
With that i get unique dates but the emmission for the last element is zero
Upvotes: 3
Views: 47
Reputation: 40861
one typo: "emmission" is spelled "emission"
a possible solution would use two loops. First to sum all the emissions grouped by date as a key, and then second to rebuild the object.
<?php
$json = '[
{
"date": "04-06-2016",
"emission": 3450
},
{
"date": "04-06-2016",
"emission": 91
},
{
"date": "09-02-2016",
"emission": 10
},
{
"date": "04-06-2016",
"emission": 7
},
{
"date": "19-04-2016",
"emission": 28
},
{
"date": "08-05-2015",
"emission": 7
},
{
"date": "04-06-2016",
"emission": 15
},
{
"date": "04-06-2016",
"emission": 109
}
]';
$arr_obj = json_decode($json);
// for each record, if date emission is set, then sum, else set emission
foreach ($arr_obj as $record)
$dates[$record->date] = isset($dates[$record->date]) ? $dates[$record->date] + $record->emission : $record->emission;
// create array of objects
foreach ($dates as $key => $val)
$obj_arr []= (object) array("date"=>$key,"emission"=>$val);
$json = json_encode($obj_arr);
echo $json;
Results in this output:
[{"date":"04-06-2016","emission":3672},{"date":"09-02-2016","emission":10},{"date":"19-04-2016","emission":28},{"date":"08-05-2015","emission":7}]
Upvotes: 1