2016-04-29 64 views
0

在php中,如果您使用數字索引爲表單字段命名,則它們將作爲$ _POST對象中的數組工作。php表單發佈數組訂單

<form method="post" action="post.php"> 
    <input type="text" name="question[0][name]" /> 
    <input type="text" name="question[0][email]"/> 
    <input type="text" name="question[0][password]" /> 
    <hr> 
    <input type="text" name="question[1][name]" /> 
    <input type="text" name="question[1][email]"/> 
    <input type="text" name="question[1][password]" /> 
    <hr> 
    <input type="submit" value="Add" /> 
    <hr> 
    <p><?php 

if ($_SERVER['REQUEST_METHOD'] == 'POST') { 
    echo json_encode($_POST, JSON_NUMERIC_CHECK); 
} 

    ?></p> 
</form> 

輸出

{"question":[{"name":"a","email":"aa","password":"aaa"},{"name":"b","email":"bb","password":"bbb"}]} 

如果字段的順序是不連續的,從零開始以及每個名稱重複時刻只能有一個遞增,然後他們都解釋爲鍵,而不是。所以

<form method="post" action="post.php"> 
    <input type="text" name="question[1][name]" /> 
    <input type="text" name="question[1][email]"/> 
    <input type="text" name="question[1][password]" /> 
    <hr> 
    <input type="text" name="question[0][name]" /> 
    <input type="text" name="question[0][email]"/> 
    <input type="text" name="question[0][password]" /> 
    <hr> 
    <input type="submit" value="Add" /> 
    <hr> 
    <p><?php 

if ($_SERVER['REQUEST_METHOD'] == 'POST') { 
    echo json_encode($_POST, JSON_NUMERIC_CHECK); 
} 

    ?></p> 
</form> 

輸出

{"question":{"1":{"name":"a","email":"aa","password":"aaa"},"0":{"name":"b","email":"bb","password":"bbb"}}} 

有沒有辦法讓$ _ POST忽略後按鍵排列的順序,以便它們被解釋爲一個數組?

+0

另一種方式是,當GET排序$ _POST陣列。 –

+0

@ShivaniPatel你的這個例子? – frumbert

回答

1

請檢查是否有幫助與否:

<form method="post" action="#"> 
    <input type="text" name="question[1][name]" /> 
    <input type="text" name="question[1][email]"/> 
    <input type="text" name="question[1][password]" /> 
    <hr> 
    <input type="text" name="question[0][name]" /> 
    <input type="text" name="question[0][email]"/> 
    <input type="text" name="question[0][password]" /> 
    <hr> 
    <input type="submit" value="Add" /> 
    <hr> 
    <p> 
<?php 
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {      
      ksort($_POST['question']);   
      print_r($_POST['question']); 
    } 

?> 
</p> 
</form> 
+0

它將根據鍵對數組進行排序。 –

+0

在我的第一個代碼中,無論域名是什麼。在「修復」中,字段名稱必須提前知道。有沒有辦法對POST對象中的所有字段名進行排序,而不必知道它們的名字? – frumbert

+0

請檢查這有幫助與否,我有這樣的功能:http://i.imgur.com/8yfZN0f.png和輸出是http://i.imgur.com/7SiRiaR.png –