我正在尝试编写一个foreach循环,它将通过邮件为每个数组元素发送一个单独的报告,但它只保留输出最后一个元素。我试过写这么多的方式,我想我开始重复自己了。请帮忙。
$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>';}
}
数组中有15个项目,报告的电子邮件工作得很好,但报告中的数据是最后一项15x。有更多的数据,并且有一个静态变量,我有数组元素,它可以很好地工作,但我需要循环,因为我必须在很多地方使用这些数据。
答案 0 :(得分:0)
您需要设置数组以包含所有检索到的值。
$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>';
}
}
然后可能在您的报告中,您有一个循环继续使用$wtdVar
或$wtdgoal
- 相反,这应该使用$wtdVars[$i]
和$wtdgoals[$i]
,其中$i
是变量从零开始,随着报表循环的每次迭代而递增。