Foreach Loop repeats the last element in an array

I am trying to write a foreach loop that will send a separate report by mail for each element of the array, but it will only output the last element. I tried to write in so many ways that I think I'm starting to repeat. Please, help.

$items = array(1 => 1, 2 => 2, 3 => 3, 7 => 4, 8 => 5,9 => 6, 17 => 8, 18 => 338, 19 => 50, 23 => 52, 11 => 7, 16 => 44, 4 => 11, 5 => 22, 6 => 33); foreach ($items as $id => $number) { //I am querying a pervasive database here $wtdVar = $dbx->getOne('SELECT SUM(sales) FROM table WHERE date1 >= '.$wkstart3.' AND date2 <= '.$today3.' AND category <> \'ABC\' AND number = '.$number); if (DB::isError($wtdVar)) { echo '<div class="error">Error: - '.$wtdVar->getDebugInfo().'</div>'; } //get the goal for the week so far, use date variables with 2 at the end for postgres queries $wtdgoal = $db->getOne("SELECT SUM(goal) FROM table2 WHERE id = $id AND gdate BETWEEN '$wkstart2' AND '$today2'"); if (DB::isError($wtdgoal)) { echo '<div class="error">Error: - '.$wtdgoal->getDebugInfo().'</div>';} } 

There are 15 elements in the array, and the report email is working fine, but the data in the report is the last 15x element. There is more data, and with a static variable, where I have array elements, it works fine, but I need it to work in a loop, because I have to use this data in many places.

+4
source share
1 answer

You need to configure arrays to store all the values ​​received.

 $wtdVars = array(); $wtdgoals = array(); foreach ($items as $id => $number) { //I am querying a pervasive database here $wtdVar = $dbx->getOne('SELECT SUM(sales) FROM table WHERE date1 >= '.$wkstart3.' AND date2 <= '.$today3.' AND category <> \'ABC\' AND number = '.$number); $wtdVars[] = $wtdVar; if (DB::isError($wtdVar)) { echo '<div class="error">Error: - '.$wtdVar->getDebugInfo().'</div>'; } //get the goal for the week so far, use date variables with 2 at the end for postgres queries $wtdgoal = $db->getOne("SELECT SUM(goal) FROM table2 WHERE id = $id AND gdate BETWEEN '$wkstart2' AND '$today2'"); $wtdgoals[] = $wtdgoal; if (DB::isError($wtdgoal)) { echo '<div class="error">Error: - '.$wtdgoal->getDebugInfo().'</div>'; } } 

Then, presumably, in your report you have a loop that continues to use $wtdVar or $wtdgoal - instead, you should use $wtdVars[$i] and $wtdgoals[$i] , where $i is a variable starting from zero, which increases with each iteration of the loop in the report.

0
source

All Articles