PHP中的HTML数组字段解析

HTML Array Fields Parsing in PHP

本文关键字:字段 数组 中的 HTML PHP      更新时间:2023-09-26

我有一个这样的表单设置:

<form action="/clients/{{ $client->id }}/create-invoice" method="post">
    <div class="form-group">
        <label for="due_date" class="sr-only">Due Date</label>
        <input type="date" name="due_date" class="form-control" placeholder="Due Date">
    </div>
    <hr />
    <p class="clearfix">
        <strong class="pull-left">Invoice Items</strong>
        <a id="add_invoice_item" class="pull-right"><span class="fa fa-plus"></span></a>
    </p>
    <div class="form-group invoice_item">
        <div class="row">
            <div class="col-ms-6 col-sm-8">
                <input type="text" name="item_description[]" class="form-control" placeholder="Description">
            </div>
            <div class="col-ms-3 col-sm-2">
                <input type="number" class="form-control" name="item_quantity[]" placeholder="Quantity">
            </div>
            <div class="col-ms-3 col-sm-2">
                <input type="text" class="form-control" name="item_price[]" placeholder="Price">
            </div>
        </div>
    </div>
    <div class="form-group">
        <input type="hidden" name="_token" value={{ csrf_token() }}>
        <button class="btn-primary btn btn-block">Create Invoice</button>
    </div>
</form>

我使用的是Laravel 5.2。

我有以下jQuery来允许用户添加更多的发票项目:

$("#add_invoice_item").click(function(){
    $(".invoice_item").first().clone().insertAfter("div.invoice_item:last").find("input[type='text']").val("");
});

问题是当我看到请求时:

public function store(Request $request, Client $client)
{
    return $request->all();
}

返回如下:

{
  "due_date": "2016-11-19",
  "item_description": [
    "Website Development",
    "SEO",
    "Server Setup"
  ],
  "item_quantity": [
    "1",
    "1",
    "1"
  ],
  "item_price": [
    "450.00",
    "300.00",
    "100.00"
  ],
  "_token": "7tUMdXX9FBU4a7cug51oBlrRyeBi9H8ucUNltQgM"
}

虽然这是预期的结果,但我不确定如何让它以一种易于使用的方式返回。

例如,我需要的不是3个不同的数组列表,而是一个数组列表,每个数组列表包含每个行对象的每个字段。

:

它会返回这个:

{
  "due_date": "2016-11-19",
  "items": [
    {"description": "Server Setup", "price": "100.00", "quantity": "1"},
    {"description": "SEO", "price": "300.00", "quantity": "1"},
    {"description": "Website Development", "price": "450.00", "quantity": "1"}
  ],
  "_token": "7tUMdXX9FBU4a7cug51oBlrRyeBi9H8ucUNltQgM"
}

我认为我需要改变的HTML和jQuery,但我不确定如何得到它的工作,使jQuery添加新的字段正确并进入items的数组

谢谢!

将数组命名为product[i][field]

<input type="text" name="product[0][description]"/>
<input type="text" name="product[0][quantity]"/>
<input type="text" name="product[0][price]"/>
<input type="text" name="product[1][description]"/>
<input type="text" name="product[1][quantity]"/>
<input type="text" name="product[1][price]"/>

在PHP中你会收到这个:

var_dump($_POST['product']);
[
    [
        'description': 'Website development',
        'quantity': '1',
        'price': '450.00'
    ],
    [
        'description': 'SEO',
        'quantity': '1',
        'price': '300.00'
    ],
]

唯一的缺点是你需要手动设置数组索引。


使用jQuery和模板:

var index = 0;
function add() {
  $('.form').append(template('#my-template', {
    i: index
  }));
  index++;
}
function template(selector, params) {
  if (typeof params === 'undefined') {
    params = [];
  }
  var tplEl = $(selector);
  if (tplEl.length) {
    var tpl = $(selector).html();
    $.each(params, function(i, n) {
      tpl = tpl.replace(new RegExp("''{" + i + "''}", "g"), function() {
        if (typeof n === 'object') {
          return n.get(0).outerHTML;
        } else {
          return n;
        }
      });
    });
    return $(tpl);
  } else {
    console.error('Template "' + selector + '" not found!');
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onClick="add()">Add more</button>
<hr/>
<div class="form">
</div>
<script type="text/jQuery-tpl" id="my-template">
  <div class="row">
    {i}: 
    <input type="text" name="product[{i}][description]" />
    <input type="text" name="product[{i}][quantity]" />
    <input type="text" name="product[{i}][price]" />
  </div>
</script>

啊,这必须在jQuery中完成。嗯,这也很简单。像这样做:

$('.invoice_item').each(function(i, el) {
    // i holds the index. Use it to alter the checkboxes
    $(this)
        .find('input[name="item_description[]"]')
        .attr('name', 'item_description[' + i + ']');
    // Do the same for price and quantity
});

张贴表单时,项属性将按每行分组。