php表单后数组顺序


php form post array order

在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键数组的顺序,从而将它们解释为数组?

请检查是否有用:

<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>