2012-03-22 37 views
0

在我的名單裏有輸入框的一些名字,它遵循的1 2 3的順序....,如何知道我在php中發佈的值是什麼?

<input type= "text" name="text1"> 
<input type= "text" name="text2"> 
<input type= "text" name="text3"> 

,這意味着後名稱=文本1文本2文本3

然而,由於數量不固定,我沒有多少文本框實際存在,我如何得到所有名稱後,我張貼表格?

謝謝

回答

5

使用text[]爲您的所有輸入元素,而不是text1,名text2等,你可以再拿到值$_POST['text'],這將是一個數組。該數組將包含與表單包含的文本框一樣多的值。

更新:如果你不能改變的HTML(這是不幸的),你可以這樣做,得到的提交變量的名稱:

$names = array_filter(array_keys($_POST), 
         function ($k) { return substr($k, 0, 4) == 'text'; }); 
+0

還有其他方法嗎?因爲我由於某種原因無法將名稱更改爲數組 – 2012-03-22 12:58:35

+0

@LeoChan:查看更新。 – Jon 2012-03-22 13:06:00

+0

對不起,我怎麼稱呼這個功能? – 2012-03-22 13:11:03

0

您可以通過$_POST陣列本身只是重複

只是做然而,foreach loop記住,最好是知道什麼正在傳遞的價值觀,做一個趕上所有這樣的動作,你打開自己可能的注射和攻擊。

2
foreach($_POST as $name => $value) { 
     echo "$name = $value"; 
} 

應該給你的想法

或者您可以使用數組文本[]:

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

Yo你可以包含一個隱藏的字段,其值是所有這些字段的名稱。

PUT THIS IN THE HTML FORM 
<input type= "text" name="text1" value="1" /> 
<input type= "text" name="text2" value="2" /> 
<input type= "text" name="text3" value="3" /> 
<input type="hidden" name="textContainer" value="text1,text2,text3" /> 

然後,您可以在PHP得到這個變量是這樣的:

<?php 
    $textFields = trim($_POST[ 'textContainer' ]); 
    $textFields = explode(',', $textFields); 

    $fields = array(); // this array will contain all text fields with names text1, text2 as keys 
    foreach($textFields as $key => $value) { 
     $fields[ $value ] = $_POST[ $value ]; 
    } 

    /* $fields is now an array like below: 
    Array (
     'text1' => 1, 
     'text2' => 2, 
     'text3' => 3 
    )*/ 
?> 

讓我知道這是否正常工作。

+0

@ leo-chan - 讓我知道這是否可行。您可以將隱藏字段值設置爲您要檢查的所有字段名稱。 – 2012-03-22 13:20:59

相關問題