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 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起