N
N
nikaose2020-05-17 18:18:55
PHP
nikaose, 2020-05-17 18:18:55

How to sum the keys of a multidimensional array by condition?

Hello,
I can not solve the problem with a multidimensional array:

Here is the array

Array
(
[0] => Array
(
[Name] => Group1
[UserID] => 178808601
[Stars] => 43
[Date] => 2020-05-11 10:17:50
)
[1] => Array
(
[Name] => Group2
[UserID] => 175654534
[Stars] => 32
[Date] => 2020-04-24 13:26:42
)
[2] => Array
(
[Name] => Group1
[UserID] => 145654534
[Stars] => 10
[Date] => 2020-02-15 19:26:42
)
[3] => Array
(
[Name] => Group6
[UserID] => 165708607
[Stars] => 5
[Date] => 2020-01-24 15:00:42
)
);


Name is the name of the group. Each user (UserID) has their own Stars points.
Is there some kind of loop with a check here, or how to go through this array and sum up the points for the group?
To end up with something like this
Such

Array
(
[0] => Array
(
[Name] => Group1
[Stars] => 53
)
[1] => Array
(
[Name] => Group2
[Stars] => 32
)
[2] => Array
(
[Name] => Group6
[Stars] => 5
)
);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nokimaro, 2020-05-18
@nikaose

If a cycle in the forehead

<?php
$sum = [];
foreach($arr as $row)
{
    if(!isset($sum[$row['Name']]))
    {
        $sum[$row['Name']] = [
             'Name' => $row['Name'],
             'Stars' => 0,
        ];
    }

    $sum[$row['Name']]['Stars'] += $row['Stars'];
}
$sum = array_values($sum);

print_r($sum);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question