猿问

laravel post 表单中的对象映射

您好,我不确定如何正确提问,但我面临的问题是将表单正文序列化为对象:


我有表格:


<form method="POST" action="{{ route('action') }}">

  <table>

    @foreach($items as $item)

     <td>

       <input name="name[]" value={{ $item->price }}>

     </td>

     <td>

       <input name="price[]" value={{ $item->name }}>

     </td>

    @endforeach

  <table>

</form>

将数据发送给我:


[

    "name" =>  [

        0 => "camera",

        1 => "toy"

    ],

    "price" =>  [

        0 => "120",

        1 => "120"

    ]

]

有没有一种正确的方法可以从这个字段创建一个合适的对象或数组,如下所示:


[ "name" => "camera", "price" => "120" ],

[ "name" => "120", "price" => "120" ]

我知道我可以使用循环......但是有 Laravel 的方法吗?


隔江千里
浏览 127回答 2
2回答

明月笑刀无情

您可以重建您的表单,注意name属性:<form method="POST" action="{{ route('action') }}">&nbsp; <table>&nbsp; &nbsp; &nbsp;<!-- btw, where's tr tag? -->&nbsp; &nbsp; &nbsp;<td>&nbsp; &nbsp; &nbsp; &nbsp;<input name="items[0][name]" value={{ $item->price }}>&nbsp; &nbsp; &nbsp;</td>&nbsp; &nbsp; &nbsp;<td>&nbsp; &nbsp; &nbsp; &nbsp;<input name="items[0][price]" value={{ $item->name }}>&nbsp; &nbsp; &nbsp;</td>&nbsp; &nbsp; &nbsp;<td>&nbsp; &nbsp; &nbsp; &nbsp;<input name="items[1][name]" value={{ $item->price }}>&nbsp; &nbsp; &nbsp;</td>&nbsp; &nbsp; &nbsp;<td>&nbsp; &nbsp; &nbsp; &nbsp;<input name="items[1][price]" value={{ $item->name }}>&nbsp; &nbsp; &nbsp;</td>&nbsp; &nbsp; &nbsp;<!-- etc -->&nbsp; <table></form>通过这样的命名,您将拥有$_POST['items']所需结构的子数组。注意属性中的显式索引name。类似的命名item[][name]将无法正常工作。

陪伴而非守候

在渲染模板之前,您可以使用array_combine ( array $keys , array $values )处理数据:array$items = [&nbsp; &nbsp; "name" =>&nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 0 => "camera",&nbsp; &nbsp; &nbsp; &nbsp; 1 => "toy"&nbsp; &nbsp; ],&nbsp; &nbsp; "price" =>&nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 0 => "120",&nbsp; &nbsp; &nbsp; &nbsp; 1 => "120"&nbsp; &nbsp; ]];$items = array_combine($data['name'], $data['price']);渲染后,在模板中使用foreach()您可以在表中填充您的数据<table>&nbsp; &nbsp; @foreach($items as $name => $price)&nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; <td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<input name="name[]" value={{ $name }}>&nbsp; &nbsp; &nbsp; &nbsp; </td>&nbsp; &nbsp; &nbsp; &nbsp; <td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<input name="price[]" value={{ $price }}>&nbsp; &nbsp; &nbsp; &nbsp; </td>&nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; @endforeach<table>
随时随地看视频慕课网APP
我要回答