2009-07-16 18 views
8

我分析別人的PHP代碼,我已經注意到,輸入HTML具有名稱以「[]」終結,許多隱藏的輸入字段,例如:在隱藏的HTML輸入用方括號字段

<input type="hidden" name="ORDER_VALUE[]" value="34" /> 
<input type="hidden" name="ORDER_VALUE[]" value="17" /> 

用於處理此輸入PHP頁面獲得這樣每個值:

foreach ($_REQUEST["ORDER_VALUE"] as $order_value) { 
    /... 
} 

什麼是「[]」用的?指定將有多個具有相同名稱的輸入字段?

回答

11

是的。基本上PHP會知道將所有這些具有相同名稱的值粘貼到一個數組中。

這適用於所有輸入字段,順便說一下,不僅僅是隱藏的。

1

大多數表單處理庫希望作者聲明他們是否想將一段數據視爲字符串或字符串數​​組。

PHP的作者決定與世界其他地方不一致,並要求專門構建HTML。

將方括號放在名稱的末尾告訴PHP將其視爲一組數據。

14

它將數據作爲數組傳遞給PHP。當你有相同名稱的HTML表單時,它會附加到逗號列表中,如複選框列表。這裏PHP有處理將其轉換成基於上的[]像這樣一個PHP數組:

,讓您的結果被當成array發送到PHP腳本,要對,或元素是這樣的:

<input name="MyArray[]" /> 
<input name="MyArray[]" /> 
<input name="MyArray[]" /> 
<input name="MyArray[]" /> 

注意變量名後的方括號,這就是它的一個數組。你可以把單元分組到不同的數組由分配相同的名字,以不同的元素:

<input name="MyArray[]" /> 
<input name="MyArray[]" /> 
<input name="MyOtherArray[]" /> 
<input name="MyOtherArray[]" /> 

這將產生兩個數組,MyArray和MyOtherArray,併發送給PHP腳本。它也可以對特定的密鑰數組分配:

<input name="AnotherArray[]" /> 
<input name="AnotherArray[]" /> 
<input name="AnotherArray[email]" /> 
<input name="AnotherArray[phone]" /> 

http://us2.php.net/manual/en/faq.html.php