How can I sum this object

can someone help me on this please, I want to sum all the x,y and total with the same id

array (size=3)
  0 => 
    object(stdClass)[13]
      public 'id' => string '24' (length=2)
      public 'x' => float 2
      public 'y' => float 5
      public 'total' => int 7
  1 => 
    object(stdClass)[17]
      public 'id' => string '25' (length=2)
      public 'x' => int 0
      public 'y' => float 2
      public 'total' => int 2
  2 => 
    object(stdClass)[19]
      public 'id' => string '25' (length=2)
      public 'x' => float 13
      public 'y' => int 0
      public 'total' => int 13

Thank you in advance.

Without seeing and understanding your data I can’t guarantee that the below will work, but it may help.

$data = [
    /**
     * The data that you want to sum.
     */
];

$totals = array_reduce($data, function ($carry, $item) {
    $id = $item->id;
    
    if (!isset($carry[$id])) {
        $carry[$id] = $item;
    } else {
        $carry[$id]->x += $item->x;
        $carry[$id]->y += $item->y;
        $carry[$id]->total += $item->total;
    }
  
    return $carry;
    
}, []);

foreach($totals as $id => $item) {
    printf("\n   id: %s\n    x: %s\n    y: %s\ntotal: %s\n", 
        $id, 
        $item->x, 
        $item->y, 
        $item->total
    );
}

Thank you for the help, I fixed it now.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.