2012-06-28 48 views
0

我有一個形式,其中可以輸入幾行相同的幾次,這樣,添加在陣列甚至價值的關鍵是空的PHP

<input type="text" name="company[]"><input type="text" name="type[]"> 
<input type="text" name="company[]"><input type="text" name="type[]"> 
<input type="text" name="company[]"><input type="text" name="type[]"> 

現在我要輸入這些字段數據庫,所以我通過輸入字段循環,它工作正常。

但我有一個問題:有時循環中的字段可能爲空。即該公司將有一個價值,但不是類型。所以,我怎麼可以讓這樣的循環應該在這樣一個關鍵的輸出空值:

Array(
    company => array(
      [0] => string0 
      [1] => string1 
      [2] => string2 
    ) 
    type => array(
      [0] => 
      [1] => string1 
      [2] => string2 
    ) 
) 

所以你可以看到類型,首先關鍵是空的,所以我怎麼能做到這一點,

我想這樣做,但沒有結果,

$postFields = array('company', 'type'); 
$postArray = array(); 
foreach($postFields as $postVal){ 
    if($postVal == ''){ 
     $postArray[$postVal] = ''; 
    } 
    else { 
     $postArray[$postVal] = $_POST[$postVal]; 
    } 
} 

得到任何幫助,

+0

是否爲每個標籤添加一個'value =「」'而不是爲您做? –

+0

不,因爲我必須禁用空字段 – itsme

+0

它是'type =「text」',在'$ _POST'數組中有一個空值_will_ ...我努力在這裏看到問題/期望的輸出... – Wrikken

回答

2

此HTML:

<input type="text" name="company[]"><input type="text" name="type[]"> 

會動態填充你的數組的鍵。只要其中一個文本字段已提交,我認爲您永遠不會收到空的0元素。相反,你最終會得到不匹配的數組長度,你將無法確定哪個數字被省略。

的解決方案是明確的陳述鍵在HTML,像這樣:

<input type="text" name="company[0]"><input type="text" name="type[0]"> 
<input type="text" name="company[1]"><input type="text" name="type[1]"> 
<input type="text" name="company[2]"><input type="text" name="type[2]"> 

現在,你可以循環數組過來,如果某個鍵不,你可以將其設置爲空字符串:

foreach(range(0, 2) as $i) { 
    if(!isset($_POST['company'][$i])) 
     $_POST['company'][$i] = ""; 

    if(!isset($_POST['type'][$i])) 
     $_POST['type'][$i] = ""; 
} 
+0

這不是我的正確答案,但在我的問題所在的地方給出了正確的方向,謝謝。 – itsme