juselliott
juselliott

Reputation: 35

Group array by field and give total value

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

Answers (2)

Dave Chen
Dave Chen

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);

Output:

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

Marc
Marc

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

Related Questions