2009-08-04 41 views
3

我有一個mysql_query結果,我在代碼的不同部分多次循環,每次使用mysql_data_seek($ result,0)重置爲結果的開始。如何刪除通過mysql_query獲取的特定行結果?

我對這些結果使用了mysql_fetch_array,並且想要從$ result中刪除一些特定的行。基本上相當於unset($ result [$ row]),如果它是一個普通的數組。有沒有辦法做到這一點?

示例代碼:

$result = mysql_query($sql); 
$num_rows = mysql_num_rows($result); 
if($num_rows){ 
    for($a=0; $a < $num_rows; $a++){ 
    $row = mysql_fetch_array($result); 
    if(my_check_function($row['test']){ 
       // do stuff 
    } else { 
      // remove this row from $result 
    } 
    } 
} 
mysql_data_seek($result, 0); 

我知道我可以簡單地做復位($行[$一])來去除特定行,但之後的數據尋求並通過成果我循環下一次我結束與原始結果行相同。

任何幫助,將不勝感激。 ps - 不知道爲什麼_在我的頂部文本中被刪除並更改爲斜體,我試圖修復它,但它最終變成了粗體.. :)

回答

7

最好的選擇是重新編寫你的查詢,讓你在對數據庫運行查詢後,不必刪除任何記錄。也就是說,或者將你的記錄插入到另一個數組中,而僅僅跳過那些你不想要的記錄。

$survivors = array(); 

while ($row = mysql_fetch_array($result)) { // while we have records 
    if (do_something($row))     // if this is a good record 
    $survivors[] = $row;     // save it for later 
} 

print_r($survivors);      // who survived the cut? 
+0

好的,謝謝,那就是我最終做的。我很好奇,如果有一種方法可以直接改變mysql_query的結果本身,不要猜測:) – Rob 2009-08-05 01:22:22

2
$result = mysql_query($sql); 
$new_rows = mysql_num_rows($result); 
$new_array = array(); 
if($num_rows){ 
    for($a=0; $a < $num_rows; $a++){ 
    $row = mysql_fetch_array($result); 
    if(my_check_function($row['test']){ 
         // do stuff 
     // populate new array with only validated data 
     $new_array[$a] = $row; 
    } else { 
       // remove this row from $result 
      // do not remove anything. 
    } 
    } 
} 

PS。你確定你不能在你的SQL查詢中排除不必要的行嗎?

0

請爲網絡的愛,不要自己建立一個SQL查詢。使用PDO