Reputation: 35
I'm trying to group the following array by 'label' to give a total value for each person.
Array
(
[0] => Array
(
[label] => John
[value] => 84
)
[1] => Array
(
[label] => Darren
[value] => 28
)
[2] => Array
(
[label] => John
[value] => 20
)
[3] => Array
(
[label] => Morgan
[value] => 20
)
[4] => Array
(
[label] => Hannah
[value] => 14
)
[5] => Array
(
[label] => Morgan
[value] => 14
)
[6] => Array
(
[label] => Darren
[value] => 10
)
)
This would be the end result:
Array
(
[0] => Array
(
[label] => John
[value] => 104
)
[1] => Array
(
[label] => Darren
[value] => 38
)
[2] => Array
(
[label] => Morgan
[value] => 34
)
[3] => Array
(
[label] => Hannah
[value] => 14
)
)
I'm assuming I need to use foreach to group the labels together but I'm stuck for the best way to do this.
Upvotes: 0
Views: 29
Reputation: 10975
Try this:
<?php
$array = [
['label' => 'John',
'value' => '84'],
['label' => 'Darren',
'value' => '28'],
['label' => 'John',
'value' => '20'],
['label' => 'Morgan',
'value' => '20'],
['label' => 'Hannah',
'value' => '14'],
['label' => 'Morgan',
'value' => '14'],
['label' => 'Darren',
'value' => '10']
];
$final = [];
foreach ($array as $arr)
$final[$arr['label']] = isset($final[$arr['label']]) ? $final[$arr['label']] + $arr['value'] : $arr['value'];
$result = [];
foreach ($final as $label => $value)
$result[] = ['label' => $label, 'value' => $value];
print_r($result);
Array
(
[0] => Array
(
[label] => John
[value] => 104
)
[1] => Array
(
[label] => Darren
[value] => 38
)
[2] => Array
(
[label] => Morgan
[value] => 34
)
[3] => Array
(
[label] => Hannah
[value] => 14
)
)
Upvotes: 1
Reputation: 3709
I would do something like this (expecting your array in $array
):
// output array
$newArray = array();
// loop over the input array
foreach($array as $entry) {
// loop over the output array
foreach($newArray as &$currentEntry) {
// check if there is a the current label
if($currentEntry['label'] == $entry['label']) {
// if so, add the value and continue (also parent)
$currentEntry['value'] += $entry['value'];
continue 2;
}
}
// if the current label wan't found, it will get here and add an entry
array_push($newArray,$entry);
}
print_r($newArray);
Upvotes: 1