2013-02-14 85 views
4

我正在嘗試編寫一個foreach循環,它將通過郵件爲每個數組元素髮送單獨的報告,但它始終只輸出最後一個元素。我試過寫這麼多的方法,我想我開始重複自己。請幫忙。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個項目,以及報告的電子郵件工作得很好,但在報表中的數據是最後一項了15倍。有更多的數據,並有一個靜態變量,我有數組元素,它完美的工作,但我需要循環,因爲我必須在很多地方使用這些數據。

+3

您在foreach循環的每次迭代中重寫變量'$ wtdVar'和'$ wtdgoal',所以如果您希望在'$ wtdVar'或'$ wtdgoal'中獲取數據,則只會獲得最後一個結果,對應於最後一次迭代。 – tmuguet 2013-02-14 21:16:13

+0

@tmuguet你可以請更具體一點,並舉例說明它應該如何寫?這是我真正奮鬥的PHP領域之一。 – BMcG0803 2013-02-15 01:50:57

+0

我不能更具體,除非你把代碼放在你使用這些變量的地方(我猜,在foreach循環之後)。 – tmuguet 2013-02-15 10:27:29

回答

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爲零的變量出發,與報告中的每次循環遞增。