Laravel Post形式的对象映射

时间:2019-07-17 07:16:28

标签: php laravel

你好,我不确定如何正确询问,但是我面临的问题是将表单主体序列化为对象:

我有表格:

<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方法吗?

2 个答案:

答案 0 :(得分:2)

您可以按照name属性的形式重建表单:

<form method="POST" action="{{ route('action') }}">
  <table>
     <!-- btw, where's tr tag? -->
     <td>
       <input name="items[0][name]" value={{ $item->price }}>
     </td>
     <td>
       <input name="items[0][price]" value={{ $item->name }}>
     </td>
     <td>
       <input name="items[1][name]" value={{ $item->price }}>
     </td>
     <td>
       <input name="items[1][price]" value={{ $item->name }}>
     </td>
     <!-- etc -->
  <table>
</form>

通过这种命名,您将拥有$_POST['items'],其中包含所需结构的子数组。

注意name属性中的显式索引。像item[][name]这样的命名将不起作用

答案 1 :(得分:0)

在渲染模板之前,您可以使用array_combine ( array $keys , array $values ) : array

处理数据
$items = [
    "name" =>  [
        0 => "camera",
        1 => "toy"
    ],
    "price" =>  [
        0 => "120",
        1 => "120"
    ]
];

$items = array_combine($data['name'], $data['price']);

渲染后,可以在模板中使用foreach()在表中填充进行数据

<table>
    @foreach($items as $name => $price)
        <tr>
        <td>
           <input name="name[]" value={{ $name }}>
        </td>
        <td>
           <input name="price[]" value={{ $price }}>
        </td>
        </tr>
    @endforeach
<table>