循环通过形式输入数组在php [英] Loop through form input arrays in php

查看:191
本文介绍了循环通过形式输入数组在php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在CodeIgniter中构建应用程序。我有一个使用jQuery创建新订单项的发票表单。订单项的格式如下:

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" />

我无法解决的是如何循环遍历多个订单项以存储DB称为订单项。

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

目前我有

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

但我知道不能写,因为我需要以某种方式引用发票[new_item_attributes] [] [description] 将其存储在说明等中

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.

推荐答案

正确的解决方案将取决于你计划在
$ _POST ['invoice'] ['new_item_attributes ']或者如果你打算把它作为一个数组数组(换句话说,你计划使用多个new_item_attributes。)

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);
}

否则你需要在PHP代码中使用:

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']);
}

或:

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

这篇关于循环通过形式输入数组在php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆