An array computation problem

$userlist = [                
                ["name"=>"zhang","money"=>10, "level"=>1],
                ["name"=>"wang", "money"=>20, "level"=>2],
                ["name"=>"li",   "money"=>10, "level"=>3],
                ["name"=>"zhao", "money"=>30, "level"=>3],
                ["name"=>"wu",   "money"=>20, "level"=>5]
            ];

how to count out the values of money in groups according to level and output them sequentially.

if the level is the same, the money adds up. For example, for level=3, the length of the money=10+30=40,userlist array is unknown.

Php
Jun.04,2021

    $level = [];
    
    foreach ($userlist as $value) {
        $level[$value['level']] += $value['money'];
    }
    
    var_dump ($level);

result

array(4) {
  [1] =>
  int(10)
  [2] =>
  int(20)
  [3] =>
  int(40)
  [5] =>
  int(20)
}

$userlist = [                
                ['name'=>'zhang','money'=>10, 'level'=>1],
                ['name'=>'wang', 'money'=>20, 'level'=>2],
                ['name'=>'li',   'money'=>10, 'level'=>3],
                ['name'=>'zhao', 'money'=>30, 'level'=>3],
                ['name'=>'wu',   'money'=>20, 'level'=>5]
            ];


function groupby($array, $groupby_key, $sum_key){
    $res = array();
    foreach($array as $data) {
        if(!array_key_exists($data[$groupby_key], $res))
            $res[ $data[$groupby_key] ] = 0;
        $res[ $data[$groupby_key] ] += $data[$sum_key];
    }
    return $res;
}


$res = groupby($userlist, 'level', 'money');
var_dump($res);

will output

array(4) {   
  [1]=>      
  int(10)    
  [2]=>      
  int(20)    
  [3]=>      
  int(40)    
  [5]=>      
  int(20)    
}            

you don't have to think so much about this. Just use a foreach , such as @ CrazyCodes.
or consider array_reduce .

$result = array_reduce($userlist, function($res, $item){
        $res[$item['level']] += $item['money'];
        return $res;
}, []);
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b412b4-2c576.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b412b4-2c576.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?