I’m looking for the right logic to loop thru a recordset and fire an event each n times.
Searching on Google i’ve found some discussion on similar situations, but it seems that solutions don’t fits my needs.
I need to interface my app with a webservice that use minOccurs=”0″ maxOccurs=”4″ for repeatable elements in a single call. Let’s say i have a recordset of 22 rows.
I need to:
- loop thru the recordset and populate the array $data with each row
- on the 4th row (8th, 12th, 16th…) fire the event (call the WS with $data of 4 elements)
- empty $data and continue with the loop till the next 4th
- if the number of rows is not multiple of 4 i must handle the remainder and fire one last call
Using the modulus operator as shown in this answer, if($i % 4 == 0), i get the event fired each 4 rows, but 22 its not a multiple of 4 so the event is fired till the 20th row and then nothing. Maybe i need to make a division counting rows in ‘excess’?
Since the recordset will be between 50 and 200 rows i think its not necessary run multiple query of 4 rows, am I wrong?
Thanks in advance!
UPDATE:
Inspired by the answers below i finally managed to get the script work as i wanted… probably its not an elegant solution but works as expected:
$result = $query->result(); // the recordset
$total_rows = count($result);
$interleave = 4;
$reminder = $total_rows % $interleave;
$round_rows = ($total_rows-$reminder)+1; // +1 because $i dont start at zero
$data = array();
Start with a initial loop ($round_rows is a multiple of 4)
for ($i=1; $i<$round_rows; $i++){
$data[$i] = $result[$i];
if ($i % $interleave == 0){
$this->fire_event($data);
$data = array();
}
}
Then if there is a reminder, loop thru…
if ($total_rows % $interleave !== 0){
for ($i = $round_rows; $i < $total_rows + 1; $i++) {
$data[$i] = $result[$i];
}
$this->fire_event($data);
}
Any advice is welcome!
If you need to fire an event at the end of the recordset, just do it.
If you need to fire the event only when you have spare records after the last event fired then use an if
The
$iindex continue to live after the end of the loop and you can leverage on this language property