phparraysmultidimensional-arraysumgrouping

Group an array of objects by one property and sum another property within each group


I am trying to group items within a PHP foreach by their 'field->value' and get the sum of each group separately. This code below works, but I feel like there is a more efficient way of doing it?

$number_1 = 0;
$number_2 = 0;
$number_3 = 0;

foreach ( $fields as $field ) {   
  if($field->value == 1) {
    $number_1 += $field->number;
  }
  if($field->value == 2) {
    $number_2 += $field->number; 
  }
  if($field->value == 3) {
    $number_3 += $field->number; 
  }
  
}  

echo $number_1; 
echo $number_2; 
echo $number_3;

Solution

  • In this case you can use variable variables.
    Generally I would rather recommend an array but it's your choice.

    foreach ( $fields as $field ) {  
         ${"number_" . $field->value} += $field->number;
    }
    

    Array version.

    foreach ( $fields as $field ) {  
         $arr["number_" . $field->value] += $field->number;
    }
    //  Either output as array or extract values to separate variables.  
    
    Echo $arr["number_1"];
    //Or
    Extract($arr);
    Echo $number_1;
    

    Edit had number where it should be value.