2017-05-08 22 views
0

$_POST陣列是這樣的:迭代過濾鍵在查詢中使用

array(4){ 
    [4]=> string(0) "" 
    [1]=> string(1) "5" 
    [2]=> string(1) "3" 
    [3]=> string(0) "" 
} 

數組鍵代表數據庫條目的ID。所以我想嘗試使用ID的鍵來更新我的數據庫。

for($db=0; $db<count($_POST); $db++){ 
    if($_POST[$db] != NULL){ 
     $id = key(current($_POST[$db])); //<-- Problem 
     $value = $_POST[$db]; 
     // query code 
    } 
} 

$id行不起作用。有人能幫我嗎?

+1

爲什麼不直接使用foreach($ _POST as $ id => $ value)? – Igor

+1

'foreach($ _ POST爲$ id => $ value)'? – splash58

+0

謝謝大家的意見和解答。它現在有效! –

回答

0

而不是在每一個我運行一個條件檢查對$_POST陣列的測試,更好的做法是在循環前過濾$_POST,然後您可以在每次迭代時使用您的prepared statement query(出於安全原因),而不使用任何條件表達式。

從您的示例輸入中可以看出,您期待空值或數值。另外,數據庫表結構使用從1開始的自動遞增的id's是很常見的。我將提供3種不同的方法,以便您可以爲您的項目選擇最有效的方法。過濾後所有方法都將原始密鑰(id)保存在$_POST中。

方法#1:(刪除所有假-Y$_POST零肥胖型元素)

foreach(array_filter($_POST) as $id=>$value){ 
    // insert your prepared statement query code block here 
} 

方法#2:(僅允許來自元素$_POST,其值大於零)

foreach(array_filter($_POST,function($v){return $v>0;}) as $id=>$value){ 
    // insert your prepared statement query code block here 
} 

方法#3 :(只有pe從$_POST RMIT元件與該是一個整數的值)

foreach(array_filter($_POST,function($v){return is_int($v);}) as $id=>$value){ 
    // insert your prepared statement query code block here 
} 

這裏是所有三種方法的一個demonstration

此外,在Sahil的答案有一些不必要的檢查。

首先,檢查if(is_array($_POST))將總是給出true結果,因爲$_POSTsuperglobal陣列。如果你不相信我,你可以信任deceze的評論here,因爲他的用戶名後面有一顆奇特的鑽石。例外情況是,如果您使用的是Content-Type:text/xml,但肯定情況並非如此。

其次,在$_POST上檢查count()是不必要的,因爲如果數組爲空,foreach()循環將不會迭代一次。

1

在這裏,我們使用foreach迭代這個$_POST,希望這會幫助你。

更改爲:

for($db=0; $db<count($_POST); $db++){ 
    if($_POST[$db] != NULL){ 
    $id = key(current($_POST[$db])); <-- Problem 
    $value = $_POST[$db])); 

    --- here follows the query --- 
    } 

此:

<?php 
if(is_array($_POST) && count($_POST)>0) 
{ 
    foreach($_POST as $id=> $value) 
    { 
    //$id is your id 
    //$value is the value on that id  
    //--- here follows the query --- 
    } 
} 
+0

完美!我正在使用你的代碼與if! –

+0

@FabrizioCocco感謝您接受我的文章... welcome ... :) –

1

你爲什麼不使用foreach()

foreach($db as $key => $value){ 
     $key is the id you need 
}