5

我正在尝试编写一个 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。有更多的数据,并且有一个静态变量,其中我有数组元素它可以完美地工作,但我需要它循环,因为我必须在很多地方使用这些数据。

4

1 回答 1

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]where$i是一个从零开始的变量,随着报告中循环的每次迭代而递增。

于 2015-09-02T07:47:43.143 回答