2014-03-25 21 views
-1
function RemoveLightOk($onlist) { 
    $remainingvalues= array(); 
    $remainingvalues= explode('' , $onlist); 
    foreach ($remainingvalues as $key){ 

     $query = mysql_query("select * from table where id = '".$key."'"); 
     $rs= mysql_fetch_assoc($query); 
       $id = $rs["id"]; 
       // How to compare or check and matched ids are removed. return remaining values in an array how? 

    } 
    return $remainingvalues; 
} 

這裏是$onlist表示這是一個數組。像所有ID一起進入陣列。僅使用PHP。如何比較或檢查和匹配的ID被刪除。返回數組中的剩餘值如何?

回答

0

我假定下面的行具有一個錯字,因爲它沒有任何意義:

$remainingvalues= explode('' , $onlist); 

假設這是指:(值由空格分隔)

$remainingvalues= explode(' ', $onlist); 

首先移除任何非數字值列表以防止Sql注入:

$filtered = array_filter($remainingvalues, 'is_numeric'); 

然後您可以獲取所有現有值樂查詢

$query = mysql_query("select id from table where id IN (". implode(',', $filtered) . ")"; 

然後您可以創建與現有的值另一個數組:

$existing = array(); 
while ($row = mysql_fetch_assoc($query)) { 
    $existing[] = $row['id']; 
} 

然後返回這兩個數組的差異:

return array_diff($filtered, $existing) 
+0

我正在使用這個array_diff()函數。但我有這個問題。 array_diff():參數#1不是數組。如何解決這個問題.. – user3458420

+0

array_diff的參數#1被過濾了嗎?你用array_filter初始化後修改它嗎? (順便說一句,我編輯了我的答案在查詢中的一個小修改) – mesutozer

0

可以使用;

function RemoveLightOk($onlist) { 
    $remainingvalues= array(); 
    foreach ($onlist as $k => $v){ 

     $query = mysql_query("select * from table where id = '".$v."'"); 
     $rs= mysql_fetch_assoc($query); 
     if (!empty($rs["id"]) { 
      $remainingvalues[] = $v; 
     } 

    } 
    return $remainingvalues; 
} 

警告:我建議你不要使用mysql_query。這是從PHP文檔頁面;

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

相關問題