Search code examples
phparraysobject

PHP: group array of objects by id, while suming up object values


I'm having a hard time manipulating an array of objects in PHP. I need to group the objects by id, while summing up the points.

Starting array of objects:

[
  {
    "id": "xx",
    "points": 25
  },
  {
    "id": "xx",
    "points": 40
  },
  {
    "id": "xy",
    "points": 40
  },
]

What I need:

[
  {
    "id": "xx",
    "points": 65
  },
  {
    "id": "xy",
    "points": 40
  },
]

As a frontender, I'm having a hard time with object/array manipulations in PHP. Any help would be greatly appreciated!


Solution

  • i hope this answer help you first i will change objects to array and return the result to array again

     $values =[
      [
        "id"=> "xx",
        "points"=> 25
      ],
      [
        "id"=> "xx",
        "points"=> 40
      ],
      [
        "id"=> "xy",
        "points"=> 40
      ],
    ];
    $res  = array();
    foreach($values as $vals){
      if(array_key_exists($vals['id'],$res)){
        $res[$vals['id']]['points']    += $vals['points'];
        $res[$vals['id']]['id']        = $vals['id'];
      }
      else{
        $res[$vals['id']]  = $vals;
      }
    }
    $result = array();
    foreach ($res as $item){
      $result[] = (object) $item;
    }
    

    output enter image description here