Laravel从表单传递数组并在控制器中解析 [英] Laravel pass array from form and parse in controller

查看:54
本文介绍了Laravel从表单传递数组并在控制器中解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类似的输入数组:

I have a array of inputs like bellow:

<input type='hidden' name='sheepNames[]' value='bab' />
<input type='hidden' name='sheepNames[]' value='harry' />
<input type='hidden' name='sheepTitles[]' value='leader' />
<input type='hidden' name='sheepTitles[]' value='sheep' />

在我的控制器中,我需要遍历数组并将它们保存在具有列nametitle

In my controller I need to loop through the arrays and save them in a database with columns name and title

bab | leader <br>
harry | sheep

  $array = $request->get('sheepNames');

  foreach($array as $i => $item)
  {
    $tb_name->name= $array[$i];
    $tb_name->title= $request->get('sheepTitles')[$i];
  }

尝试了多种访问数组的方法,但似乎无法弄清楚.

Tried numerous ways of accessing the array but can't seem to figure it out.

推荐答案

使用两个数组可能更容易做到这一点.

Might be easier to do this with a couple of arrays.

$names = $request->get('sheepNames');
$titles = $request->get('sheepTitles');

$max = count($names);
for ($x = 0; $x <= $max; $x ++){
    $tb_name[$x]['name']= $names[$x];
    $tb_name[$x]['title'] = $titles[$x];
}

我不知道$ tb_name是什么,但是上面的方式,它会不断被覆盖,因此我将其作为一个数组来说明这一点.

I don't know what $tb_name is, but the way you had it above, it would keep getting written over, so I made it an array to make the point.

此外-您需要对标题的数量进行一些错误检查,以确保它们==名称,否则,标题数组上的索引可能会损坏.

Also - you need to put some error check on the count of titles to make sure they == names, else you will have a broken index on the titles array possibly.

这篇关于Laravel从表单传递数组并在控制器中解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆