我认为这样的表单:
<form action="http://localhost/RenderForm/public/handle-form" method="POST">
<input type="hidden" name="_token" value="BOwsdSS3Zc4oI08wDutUQbvtQhGvGZXBgxaOoOFD">
<div class="links">
<div>
First Name:<br>
<input name="firstName" type="text">
</div>
<br>
</div>
<div class="links">
<div>
Last Name:<br>
<input name="lastName" type="text">
</div>
<br>
</div>
<div class="links">
<div>
Location:<br>
<select name="location">
<option value="0">HN</option>
<option value="1">HCM</option>
</select>
</div>
<br>
</div>
<div>
<button type="submit">Reset Form</button>
<button type="submit">Complete Task</button>
</div>
</form>
在我的控制器中,我使用$ request-> all()获取所有表单值并将其存储到变量中。之后,我使用json_encode将其转换为Json对象。
当我调试该变量时,它具有以下值:
“ {”名字“:” hao“,”姓氏“:”阮“,”位置“:” 0“}”
但是我真正需要的是:
[ { “ id”:“名字”, “ value”:“ hao” }, { “ id”:“ lastName”, “ value”:“ nguyen” }, { “ id”:“位置”, “值”:“ 0” }]
您能告诉我如何解决此问题吗?非常感谢你!
答案 0 :(得分:1)
使用foreach循环并自定义所有输入,例如:
$collect = []; // empty array for collect customised inputs
foreach($request->all() as $input_key => $input_value){ // split input one by one
$collect[] = array( //customised inputs
"id" => $input_key,
"value" => $input_value
);
}
$result = json_encode($collect); //convert to json