Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping and adding values multidimensional array

Code

foreach ($summary as $split) {
    if (isset($split['currency'])) {
        if (!isset($result[$split['currency']]) {
            $result[$split['currency']] = [
                'duration' => 0,
                'cost' => 0
            ];
        }
        $result[$split['currency']]['employee'] = $split['employee'];
        $result[$split['currency']]['duration'] += $split['duration'];
        $result[$split['currency']]['cost'] += $split['cost'];
    } else {
        $result[0]['employee'] = $split['employee'];
        $result[0]['duration'] += $split['duration'];
        $result[0]['cost'] += $split['cost'];
    }
}

My array looks like this

$summary = Array
(
[0] => Array
   (
    [employee] => John
    [currency] => SGD
    [duration] => 8.00
    [cost] => 228.57
)

[1] => Array
   (
    [employee] => Fil
    [currency] => SGD
    [duration] => 8.00
    [cost] => 228.57
 )

[2] => Array
(
    [employee] => John
    [currency] => 
    [duration] => 8.00
    [cost] => 
)

[3] => Array
(
    [employee] => John
    [currency] => MYR
    [duration] => 12.00
    [cost] => 342.86
)

[4] => Array
(
    [employee] => Sam
    [currency] => SGD
    [duration] => 8.00
    [cost] => 228.57
)

[5] => Array
(
    [employee] => Fil
    [currency] => MYR
    [duration] => 12.00
    [cost] => 342.86
)

I want to group the above array by employee and currency. What I require is similar to Stackoverflow

but in this grouping is done for currency only so in the output array there will be 3 inner array only.

I want to group the array such that the result will group first employee and then currency. So there will be 3 inner array for each employee

like image 943
code_boy Avatar asked May 13 '26 17:05

code_boy


1 Answers

just add the name as the key in $result array before currency key,

foreach ($summary as $split) {
        if (isset($split['currency'])) {
            if (!isset($result[$split['employee']][$split['currency']]) {
                $result[$split['employee']][$split['currency']] = [
                    'duration' => 0,
                    'cost' => 0
                ];
            }
            $result[$split['employee']][$split['currency']]['employee'] = $split['employee'];
            $result[$split['employee']][$split['currency']]['duration'] += $split['duration'];
            $result[$split['employee']][$split['currency']]['cost'] += $split['cost'];
        } else {
            $result[0]['employee'] = $split['employee'];
            $result[0]['duration'] += $split['duration'];
            $result[0]['cost'] += $split['cost'];
        }
    }
like image 166
Parth Mahida Avatar answered May 15 '26 08:05

Parth Mahida