php - 循环遍历php中的表单输入数组

标签 php mysql arrays forms codeigniter

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

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

我无法解决的是如何循环遍历多个行项目并将其存储在称为行项目的数据库中。

现在我有

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

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

任何帮助将不胜感激。

最佳答案

正确的解决方案取决于您是否计划将标量值存储在 $_POST['invoice']['new_item_attributes'] 或者如果您计划将其设为数组的数组(换句话说,您计划拥有 new_item_attributes 的倍数。

如果您只计划存储标量值,那么您首先需要将每个表单元素更改为如下所示:

name="inovoice[new_item_attributes][description]"

您会注意到空的 [] 消失了。

然后你的循环应该如下所示:

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

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

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 - 循环遍历php中的表单输入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1736581/

相关文章:

php - 在 MySQL 中存储列表的正确方法是什么?

Mysql - 汇款 : Transfer data from one field to another in the same table

javascript - 循环遍历页面中的对象,如果页面包含键,则追加值

php - Laravel 5.3 抛出错误表单请求

带数组的 PHP getter 和 setter

php - 数据库查询结果codeigniter后无法调用php函数

c - 如何在c中打印数组的最后一个元素

java - 将 vector 字符串解析为字符串?

php - Doctrine2 + ZF2 - 迭代子类别

php - 在谷歌图表上放置值