2012-05-29 21 views
0

我試圖將一些信息從數據庫傳遞到HTML以顯示給我的用戶。每當「行業」發生變化時,我都想打印新標籤。我試圖使用一個名爲$ last_industry的變量來追蹤我目前正在迭代的行業是否與最後一個行業相同,但是我沒有很好的結果。我在下面粘貼了我的代碼。 $ c ['user_industries_title']是我需要監控的。在foreach結尾處更改其值的變量()

$last_industry = 'foo'; 

foreach($case_studies as &$c) { 
    //If the last industry we iterated over is different than the one we're currently iterating over, close the last section and print a new section. 
    if($last_industry != $c['user_industries_title']){ 
    echo "</section>" 
    echo "<section>"; 
    $changed = 1; 
    }else {$changed = 0} 

    $c = $last_industry; 
    $last_industry = $c['user_industries_title']; 
} 

此問題與$ last_industry變量。爲了達到這個目的,它需要將自己更新到最新的$ c ['user_industries_title'],以便在下一次迭代開始時使用,這種情況沒有發生。我錯過了什麼嗎?

+0

您在倒數第二行覆蓋'$ c'。 – Gareth

回答

2

您需要更改裏面的$ last_industry值,如果()當值發生了變化,否則你總是與同行業價值正在運行:

此外,要知道在一個陷阱中使$ ca引用(&運算符) - 它將保持腳本持續時間的參考值,並且如果您在循環退出後依賴它保持其值,則會導致奇怪的副作用。

+0

太棒了...非常感謝。這完全解決了我的問題 –

1

看看最後兩行,你重載你的$c這是一個數組,$last_industry這是你在上次迭代中使用的字符串。 將最後一行的$c重命名或完全刪除。

順便說一句:如果您將PHP error_reporting設置設置爲E_ALL,您將會收到通知,$c不再是數組!

+0

感謝您的信息。這也是相關的。 –