簡體   English   中英

foreach循環重復數組中的最后一項

[英]foreach Loop is repeating last item in array

我正在嘗試編寫一個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。 有更多的數據,並且有一個靜態變量,我有數組元素它完美地工作,但我需要它循環,因為我必須在許多地方使用這些數據。

您需要設置數組以包含所有檢索到的值。

$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是一個從零開始的變量,每增加一次迭代報告中的循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM