我使用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但由于某些原因,例如,如果所有两个属性,输出总是两倍多。我想这是由于json数组的错误格式造成的吧?
发布于 2021-04-01 23:32:30
当您给一个HTML元素name="properties[][key]"时,您在properties数组上创建了一个新元素,该数组是一个具有键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;https://stackoverflow.com/questions/66907099
复制相似问题