Laravel 5.4:如何遍历请求数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42272219/
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
Laravel 5.4: how to iterate through request array?
提问by sr9yar
My request data represents an array of new and existing items. I'm trying to through this array to update and create items.
我的请求数据表示一组新的和现有的项目。我试图通过这个数组来更新和创建项目。
This is how I retrieve the array:
这是我检索数组的方式:
$userInput = $request->all();
foreach( $userInput['items'] as $key=>&$item){
Later in the code I update an existing item:
稍后在代码中我更新了一个现有项目:
$updateItem = Item::find($item['id']);
$updateItem->number = $item['number'];
$updateItem->save();
But $item['number']
seems to contain old input from previous updates and not the value I entered last time.
但$item['number']
似乎包含以前更新的旧输入,而不是我上次输入的值。
How can I loop through request data in Laravel ?
如何在 Laravel 中循环请求数据?
This is the whole code as I run it (want to get rid of confusion):
这是我运行时的全部代码(想摆脱混乱):
$userInput = $request->all();
// checking $userInput here
// I can see the new value in the array
foreach( $userInput['items'] as $key=>$item){
if($item['delete'] == 1) {
Item::where('order_id',$order->id)
->where('id',$item['id'])
->delete();
} else {
if(empty($item['id'])) {
} else {
$updateItem = Item::find($item['id']);
$updateItem->number = $item['id'];
$updateItem->save();
}
}
}
This is an input from html (just to show I checked the form also, the data comes just fine):
这是来自 html 的输入(只是为了表明我也检查了表单,数据很好):
<input id="basicItemNumber-31" class="form-control" name="items[31][number]" placeholder="Unique number" value="31" type="text">
回答by Luke
It's likely that somewhere inside your for
you've inadvertently changed the value of your underling $item
as you pass it by reference (using the &
before the variable name.)
很可能在您内部的某个地方,您for
在$item
通过引用传递时无意中更改了下属的值(使用&
变量名之前)。
It's considered bad practice by some or most people as it can lead to "unexpected" behaviour, For example. take the sample code below that loops through an array
of $items
twice once by reference and once by value.
例如,某些或大多数人认为这是不好的做法,因为它可能导致“意外”行为。采取低于环路示例代码通过array
的$items
由值一次两次通过引用和一次。
<?php
$items = ['one','two','three'];
foreach ($items as &$item) {
//do nothing.
}
foreach ($items as $item) {
//do nothing again.
}
var_dump($items);
//outputs
array(3) {
[0]=>
string(3) "one"
[1]=>
string(3) "two"
[2]=>
&string(3) "two"
}
回答by Spholt
Try something like this as it will keep your scope local:
尝试这样的事情,因为它会使您的范围保持本地:
$request['items']->each(function($item, $key) use ($order) {
if ($item->delete) {
Item::where('order_id',$order->id)
->where('id',$item['id'])
->delete();
} else {
if (!empty($item['id'])) {
$updateItem = Item::find($item['id']);
$updateItem->number = $item['id'];
$updateItem->save();
}
}
});