未定义的偏移量甚至将 foreach 循环提交到数据库
Posted
技术标签:
【中文标题】未定义的偏移量甚至将 foreach 循环提交到数据库【英文标题】:Undefined offset even submitting foreach loop into database 【发布时间】:2020-05-08 15:59:04 【问题描述】:在我看来,我有以下 foreach 正在尝试提交并存储到我的数据库中。没有任何运气。当我尝试提交时,它返回错误Undefined offset: 70
。
这是控制器代码:
foreach ($request->useridweek1 as $key => $value)
/* $str_explode = explode("|",$value);
$numb = $str_explode[1]; */
$answer = new Retirement();
$answer->user_id = $value;
$answer->amount = $request->amountweek1[$key];;
$answer-> save();
这是我的带有 foreach 循环的视图文件:
@foreach ($request as $item)
<tbody>
<tr>
<td class="idweek1">
<input type="text" id="userid" name="userid" class="form-control" value=" $item->user_id">
</td>
<td>
<input type="text" id="marketers" name="marketers[]" class="form-control" value=" $item->marketer">
</td>
<td>
<input type="text" id="amount" name="amount[]" class="form-control" value=" $item->target * $item->AmountPbag * $fwek1) - ($item->sales->sum('sales') * $item->AmountPbag ">
</td>
<td>
<input type="text" id="mar1id" class="form-control" value=" $item->target * $item->AmountPbag * $fwek1 - $item->sales->sum('sales') * $item->AmountPbag ">
</td>
</tr>
</tbody>
@endforeach
When i dump dd($request->useridweek1);, i get
array:3 [▼
70 => "70"
72 => "72"
73 => "73"
]
When i dump . dd($request->amount);
array:3 [▼
0 => "14000"
1 => "9450"
2 => "8400"
]
【问题讨论】:
转储$request->amount
和$request->userid
的内容并检查它们是否包含相同数量的密钥。
你试过什么来调试这个问题?哪一行会发出该警告?
是的,我已经转储了这些值,它们都返回了它们的值@KFoobar
$answer->amount = $ammt[$key];这是抛出错误@NicoHaase 的行
您尝试发现什么错误? $ammt
包含什么?
【参考方案1】:
我能够使用下面的代码解决它...以防有人遇到同样的问题...使用 foreach 中的键并将 [] 添加到我刀片上的输入名称中
foreach ($request->amountweek1 as $key => $value)
$str_explode = explode("|",$value);
$numb = $str_explode;
$answer = new Retirement();
$answer->marketer = $request->marketers[$key];
$answer->amount = $value;
$answer->user_id = $request->useridweek1[$key];
$answer->week = $request->week1;
$answer-> save();
【讨论】:
以上是关于未定义的偏移量甚至将 foreach 循环提交到数据库的主要内容,如果未能解决你的问题,请参考以下文章
如何正确使用 Kafka 消费者“寻找”以返回所有分区的未提交偏移量?