首页 > 解决方案 > json 数组的格式不正确。拉拉维尔

问题描述

我正在使用 jquery 动态添加/删除产品属性的字段。然后将数据转换为json并发送到DB,我得到以下json数组:

[{"key": "123"},{"value": "21321"}]

但我想得到下一个:

[{"key": "123","value": "21321"}]

<input type="text" name="properties[][key]" class="form-control m-input ml-3" placeholder="Key" autocomplete="off">
<input type="text" name="properties[][value]" class="form-control m-input ml-3" placeholder="Value" autocomplete="off">

这就是获得正确数组的方式。但是这里的字段数量是固定的,而我的是动态的:

@for ($i=0; $i <= 4; $i++)
 <input type="text" name="properties[{{ $i }}][key]" class="form-control" value="{{ old('properties['.$i.'][key]') }}">
 <input type="text" name="properties[{{ $i }}][value]" class="form-control" value="{{ old('properties['.$i.'][value]') }}">
@endfor

我还想显示现有值进行编辑。我这样做:


@isset($product)
 @foreach($product->properties as $prod)
  <div class="input-group mb-3">
    <input type="text" name="properties[][key]" value="{{ $prod['key'] ?? '' }}" class="form-control m-input editinp-key" placeholder="Key" autocomplete="off">
    <input type="text" name="properties[][value]" value="{{ $prod['value'] ?? '' }}" class="form-control m-input ml-3 editinp-value" placeholder="Value" autocomplete="off">
  <div class="input-group-append ml-3">
    <button id="removeRow" type="button" class="btn btn-danger">Remove</button>
  </div>
 </div>
 @endforeach
@endisset

但是由于某种原因,例如,如果所有 2 个属性,输出总是多 2 倍。我想这是由于 json 数组的格式不正确?

标签: phplaravelforms

解决方案


当你给一个 HTML 元素时name="properties[][key]",你是在数组上创建一个新元素properties,它是一个带有 key 的数组key。因此,当下一个元素被命名时,name="properties[][value]"您将另一个新元素添加到属性数组中。在 PHP 中与此代码相同,其中[]创建了一个新的数组元素:

$properties[]["key"] = 123;
$properties[]["value"] = 21321;

要将这些值保持在一起,您可以使用编号数组条目而不是创建新条目。试试这个:

@foreach($product->properties as $i=>$prod)
    <input type="text" name="properties[{{ $i }}][key]" class="form-control m-input ml-3" placeholder="Свойство" autocomplete="off">
    <input type="text" name="properties[{{ $i }}][value]" class="form-control m-input ml-3" placeholder="Значение" autocomplete="off">
@endforeach

假设$product->properties是数字索引,您将$i用作计数器变量,并且应该以您正在寻找的格式结束。这就像这个 PHP 代码,其中相同的数组元素获取添加到它的键。

$i = 1;
$properties[$i]["key"] = 123;
$properties[$i]["value"] = 21321;

推荐阅读