douxuelv7755 2009-11-15 04:41
浏览 44
已采纳

在php中循环表单输入数组

I'm building an app in CodeIgniter. I have an invoice form which uses jQuery to create new line items. The line items are formated as follows:

<input type="text" name="invoice[new_item_attributes][][description]" class="ui-corner-all text invDesc" title="Description" />
<input type="text" name="invoice[new_item_attributes][][qty]" class="ui-corner-all text invQty" title="Qty" />
<input type="text" name="invoice[new_item_attributes][][amount]" class="ui-corner-all text invAmount" title="Amount" onChange="CalculateTotal(this.form)" />
<input type="hidden" name="invoice[new_item_attributes][][rowTotal]" class="row-total-input" />

What I can't work out is how can I loop through multiple line items to store then in a DB called line items.

At the moment i have

foreach ( $_POST['invoice'] as $key => $value)
    {
        $data = array(
            'description'   =>  $value;
                    );
    }   

But I know that can't be write because I need to somehow reference the invoice[new_item_attributes][][description] to store it in description etc...

Any help would be greatly appreciated.

  • 写回答

3条回答 默认 最新

  • drjtua5953 2009-11-15 04:45
    关注

    The correct solution will depend on whether you plan on storing scalar values under $_POST['invoice']['new_item_attributes'] or if you plan on making it an array of arrays (in other words, you plan on having multiples of the new_item_attributes.

    If you only plan on storing scalar values then you'll first need to change each of the form elements to look like this:

    name="inovoice[new_item_attributes][description]"
    

    You'll notice that the empty [] is gone.

    And then your loop should look like so:

    foreach($_POST['invoice']['new_item_attributes'] as $key => $val) {
        $data = array('description => $value);
    }
    

    Otherwise you'll need to use this in your PHP code:

    foreach($_POST['invoice']['new_item_attributes'] as $key => $val) {
             $data = array('description' => $val['description']);
    }
    

    Or:

    foreach($_POST['invoice']['new_item_attributes'] as $key => $val) {
         foreach($val as $sub => $value) {
             $data = array($sub => $value);
         }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?