PHP Laravel - HTML 表单值数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44517785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Laravel - HTML Forms array of values
提问by Phorce
I have the following form, with fields:
我有以下表格,带有字段:
- From
- To
- Price
- 从
- 到
- 价钱
You can add multiple rows and this data is then sent to the controller.
您可以添加多行,然后将此数据发送到控制器。
What I want is:
我想要的是:
Let's assume there are two rows of inputs currently on the page, the output would therefore be something like:
假设页面上当前有两行输入,因此输出将类似于:
$rates => array(2)
0 => [
"from" => 1,
"to" => 2,
"price" => 10
],
1 => [
"from" => 1,
"to" => 2,
"price" => 10
]
I have tried to do the following (HMTL):
我尝试执行以下操作(HMTL):
<input type="text" name="rates[]" placeholder="Enter rate from"
autocomplete="off" class="form-control">
But this just gives me an array of 6 with all the values, with no way of knowing the order. I have also tried the following:
但这只是给了我一个包含所有值的 6 数组,而无法知道顺序。我还尝试了以下方法:
<input type="text" name="rates[]['from']" placeholder="Enter rate from"
autocomplete="off" class="form-control">
<input type="text" name="rates[]['to']" placeholder="Enter rate to"
autocomplete="off" class="form-control">
<input type="text" name="rates[]['price']" placeholder="Enter rate price"
autocomplete="off" class="form-control">
This isn't producing the result(s) that I need. Is it possible to do what I want to do using HTML and PHP?
这不会产生我需要的结果。是否可以使用 HTML 和 PHP 做我想做的事情?
回答by manniL
Instead of using an index-based approach, you can use three different arrays (from
, to
and prices
e.g.). You can then iterate through all of them to get your values.
您可以使用三个不同的数组(from
、to
和prices
eg),而不是使用基于索引的方法。然后您可以遍历所有这些以获得您的值。
HTML
HTML
<input type="text" name="from[]" placeholder="Enter rate from"
autocomplete="off" class="form-control">
<input type="text" name="to[]" placeholder="Enter rate to"
autocomplete="off" class="form-control">
<input type="text" name="prices[]" placeholder="Enter rate price"
autocomplete="off" class="form-control">
PHP
PHP
$from = [
'Jane',
'Bob',
'Mary',
];
$to = [
'John',
'Alex',
'Paul',
];
$prices = [
10,
2500,
2,
];
$finalValues = [];
foreach ($prices as $i => $price) {
$finalValues[
"from" => $from[i];
"to" => $to[i];
"price" => $price;
}
This only works when your values are all required or give back null when not set
这仅在您的所有值都需要时才有效,或者在未设置时返回 null