【问题标题】:php form post array orderphp表单发布数组顺序
【发布时间】:2016-04-29 05:12:20
【问题描述】:

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

【问题讨论】:

  • 另一种方法是get时对$_POST数组进行排序。
  • @ShivaniPatel 你的例子吗?

标签: php arrays


【解决方案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>

【讨论】:

  • 它会根据键对数组进行排序。
  • 在我的第一个代码中,字段名称是什么并不重要。在“修复”中,必须提前知道字段名称。有没有办法对 POST 对象中的所有字段名称进行排序而不必知道它们的名称?
  • 请检查这是否有用,我有这样的实现功能:i.imgur.com/8yfZN0f.png,输出为i.imgur.com/7SiRiaR.png
猜你喜欢
  • 2011-03-19
  • 1970-01-01
  • 2016-05-06
  • 1970-01-01
  • 2014-09-15
  • 2011-09-03
  • 2012-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多