Search code examples
phpmoodlerecordset

adding values within an recordset where the userid is the same php


I have a recordset which is returned when I preform a mysql query from a MOODLE database.

An example of what I get:

what I am getting

What I need to do, is in the loop, calculate 'SCORE' field. If the score total is less or equal to 1, I must display each row. If the 'SCORE' exceeds 1, I must only display the records that don't add up to more than 1.

Example:

what I need

So when I perform the loop and write the records to a csv, this is what I need to display: (record 3 has been removed).

Is there a way that I can do this using a recordset?

An example (not the actual code, because it is writing to a csv and is confusing) of the code I am using is:

foreach ($recordset as $user) {
  echo 'Event Code' . $user->code . '<br />'; 
  echo 'Date' . $user->date. '<br />';
  echo 'UserId' . $user->UserId. '<br />';
  echo 'Fullname' . $user->Fullname. '<br />';
  echo 'Score' . $user->Score. '<br />';
}

Solution

  • I dont know if i understood correctly but it seems that you would do something like this:

    $sum = array();
    foreach ($recordset as $user) {
    
      if(!isset($sum[$user->UserId])) { $sum[$user->UserId] = 0; }
      $sum[$user->UserId] += $user->Score;
      if($sum[$user->UserId] > 1) { continue; }
    
      echo 'Event Code' . $user->code . '<br />'; 
      echo 'Date' . $user->date. '<br />';
      echo 'UserId' . $user->UserId. '<br />';
      echo 'Fullname' . $user->Fullname. '<br />';
      echo 'Score' . $user->Score. '<br />';
    }