BMc*_*803 5 php arrays foreach loops
我正在尝试编写一个 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>';}
}
Run Code Online (Sandbox Code Playgroud)
数组中有 15 项,报表的电子邮件工作正常,但报表中的数据是最后一项 15x。有更多数据,并且使用静态变量在其中包含数组元素,它可以完美运行,但我需要它来循环,因为我必须在许多地方使用这些数据。
您需要设置数组来包含所有检索到的值。
$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>';
}
}
Run Code Online (Sandbox Code Playgroud)
然后,大概在您的报告中,您有一个不断使用$wtdVaror 的循环$wtdgoal- 相反,应该使用$wtdVars[$i]and $wtdgoals[$i]where$i是一个从零开始的变量,该变量随着报告中循环的每次迭代而递增。
| 归档时间: |
|
| 查看次数: |
1640 次 |
| 最近记录: |