php表单发布数组顺序

时间:2016-04-29 05:12:21

标签: php arrays

在php中,如果使用数字索引命名表单字段,它们将作为$ _POST对象中的数组。

<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忽略post键数组的顺序,以便将它们解释为数组?

1 个答案:

答案 0 :(得分: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>