douque9815 2019-05-24 14:28
浏览 166

从输入创建数组?

I wish to store an arbitrary number of answers to a question on a form in a single field (json).

So the inputs may be something like:

Your Jobs:

  • job title
  • start date
  • end date

I know I can call the input <input name="job_title[]"> and these would all be listed as an array under job_title. But is there anyway to have all three inputs listed under a keyed array just by naming the inputs in a specific way, something like:

[jobs => [['job_title' => 'xyz', 'start_date` => 'xyz', 'send_date` => 'xyz'], ....]

Or would I need to build this manually in php with loops?

  • 写回答

2条回答 默认 最新

  • dtwk6019 2019-05-24 16:38
    关注

    Do you want to create an array based on the Posted input value? Just use the foreach loop with the $_POST variable like

    <?php 
    if (isset($_POST)) {
        foreach ($_POST as $key => $value) { // for every post value
            $array[] = array( // we create a array based on the name and the value
                $key => $value
            );
        }
        var_dump($array); // dump the array
    }
    ?>
    <form method="POST">
        <input type="text" name="job title" value="xyz">
        <input type="text" name="start date" value="xyz">
        <input type="text" name="send date" value="xyz">
        <!-- any other input -->
        <button type="submit">sd</button>
    </form>
    

    The var_dump($array) will give you

    array(2) { ["job_title"]=> string(3) "xyz" ["start_date"]=> string(3) "xyz" } array(1) { ["send_date"]=> string(3) "xyz" }
    

    To create JSON from the array just do

    echo json_encode($array)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答