關於mysql_fetch_object()
的一些注意事項。從PHP文件:
警告:本擴展已被棄用的PHP 5.5.0的
請注意以上。
返回具有對應於所提取的行和向前移動內部數據指針屬性的對象。
請注意我粗體字。
$result
對象(在您的代碼中,這將是$query2
)是具有指向當前項目的指針的迭代對象。
Current Item
|
v
[1][2][3][4]
當你的第一循環打你的第二個循環,它遍歷整個事情,這樣,在年底,對象現在看起來是這樣的:
Current Item
|
v
[1][2][3][4]
對於前的每一次迭代環,第一時間之後,mysql_fetch_object()
功能基本上是這樣的:
mysql_fetch_object() ~
1. Get the next time
2. Uh, there are no more objects because we're at item [4]. Return done.
那麼,你如何得到它的工作?您可以簡單地將結果保存到一個數組中,然後遍歷該數組,或者您可以使用mysql_data_seek()
(也從5.5開始不推薦使用)重置指針。
要重置數據指針,這將是這樣的:
while($row1 = mysql_fetch_object($query1)) {
echo "*".$row1->id."*";
while ($row2 = mysql_fetch_object($query2)) {
echo "%".$row2->id."%";
}
// put the result pointer back to the front
mysql_data_seek($query2, 0)
}
Note1, This SO question/answer helped me find the function to use to reset the pointer.
注意,壞處是你打電話說是創造一個對象的功能,它創建的處理開銷每次運行。
另一個選項是通過數組每次都將結果保存到一個數組,只是循環:
$secondary_result = array();
while ($row2 = mysql_fetch_object($query2)) {
$secondary_result[] = $row2;
}
while($row1 = mysql_fetch_object($query1)) {
echo "*".$row1->id."*";
foreach($secondary_result as $row2) {
echo "%".$row2->id."%";
}
}
注意,這種方法將創建存儲在數組中的對象的額外的內存使用情況,但它可以節省CPU處理,因爲您不會一遍又一遍地重新創建對象,並且可以調用一個函數。
如果您只是打印輸出,您可以考慮先保存結果。不管你現在多次循環使用$secondary_result
,最終結果總是相同的(根據你的代碼,第一個循環顯示沒有直接影響第二個結果的跡象)。
在這種情況下,這更有道理
$buffer = '';
while ($row2 = mysql_fetch_object($query2)) {
$buffer .= "%".$row2->id."%";
}
while($row1 = mysql_fetch_object($query1)) {
echo "*".$row1->id."*";
echo $buffer;
}
,但我真的不知道爲什麼你會做到這一點。如果你正在做一個嵌套循環,通常是因爲第一個循環的結果影響第二個循環。
但我希望有幫助!
乾杯!
編輯
每@ Blazemonger的約放眼望去評論,在PDO相當於將是:MySqli:Fetch-Object
當你從使用PDO功能結果對象,你會循環是這樣的:
while($row1 = $query1->fetch_object()) {
echo "*".$row1->id."*";
while ($row2 = $query1->fetch_object()) {
echo "%".$row2->id."%";
}
// put the result pointer back to the front
$query2->data_seek(0);
}
上面的例子顯示了MySqli的獲取對象和指針重置版本。
我知道轉移到PDO,這將盡快完成。 – Laurent 2013-05-01 19:12:41