douzhenchun6782 2014-09-04 22:12
浏览 35
已采纳

将可重复字段选项保存到PHP对象数组

So I am trying to save a dynamically created set of fields to the database using $_POST. Basically, I can't figure out how to get the options to save as an object for each fieldset instead of as an array of the options themselves. It's hard for me to describe... let me explain.

First, screenshot of what the thing looks like here.

The fields dynamically create via jQuery and that works great. Here's the fields I have set up for the form:

<label>Calendar Name
    <input name="name[]" id="name[]" type="text" value="<?php echo $calendars['name'][$key]; ?>">
</label>
<label>Public URL
    <input name="url[]" id="url[]" type="text" value="<?php echo $calendars['url'][$key]; ?>">
</label>
<label>Color
    <input name="color[]" id="color[]" type="text" value="<?php echo $calendars['color'][$key]; ?>">
</label>

This is similar to this question but I guess I don't understand how I should be upping and sorting the index values properly using JS, or if there is a PHP solution I'm just completely missing.

TL;DR Basically how can I produce something like foo[0]['name'] instead of foo['name'][0] using either PHP or JS or both in a dynamically created form with repeating fieldsets?

  • 写回答

2条回答 默认 最新

  • doutuobao4004 2014-09-05 15:33
    关注

    I would post processes it like so:

        if(isset($_POST['name'])) {
                // $i is how you are going to assign your keys
                $i = 0;
                // Loop through post array
                foreach($_POST['name'] as $key => $value) {
                        // Assign your new array the key values of each post array
                        $_rows[$i]['name']  =   $_POST['name'][$key];
                        $_rows[$i]['url']   =   $_POST['url'][$key];
                        $_rows[$i]['color'] =   $_POST['color'][$key];
                        $i++;
                    }
            /*   Do some quick prints to see before and after
                 echo '<pre>';
                 print_r($_POST);
                 print_r($_rows);
                 echo '</pre>';
            */
            }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验