php - Convert html form array to formated json array
问题描述
I have html input array. I want to collect the input values and return custom formatted json array. I loop through the form array and tried to collect all.
<input type="text" name="item_name[{{ i }}]">
<input type="number" name="item_price[{{ i }}]">
$item_price = $_POST['item_price'];
foreach(array_filter($_POST['item_name']) as $key => $value){
$data = array('item_name'=>$value, 'item_price'=>$item_price[$key]);
$data = array_merge($data, $data);
}
echo json_encode($data);
I want the result to be exactly like this format, having all the inputs thus. But my result only give one option, should the form request 3 items
{
"1": {
"item_name": "GOAT",
"item_price": "200"
},
"2": {
"item_name": "BEEF",
"item_price": "150"
},
"3": {
"item_name": "RAT",
"item_price": "0"
}
}
解决方案
You overwriting the $data
var each time. You should append him the data with []
as:
foreach(array_filter($_POST['item_name']) as $key => $value){
$data[] = array('item_name'=>$value, 'item_price'=>$item_price[$key]);
}
echo json_encode($data);
推荐阅读
- java - Spring WebClient 在 Tomcat 上留下开放会话
- python - 计算Python中另一个列表中每个嵌套列表的出现次数
- css - 引导按钮不会显示内联块
- reactjs - 如何在 React 中将函数设置为 useState 变量?
- r - 将数据透视表导出到 R markdown(用于 word 中的最终输出)
- java - 如何使用java动态计算模型中空字段的计数
- java - 在 Mac 上的 mvn 构建期间,Java 测试中的环境变量为空
- youtube-dl - 使用 youtube-dl 嵌入缩略图时是否可以不更改文件创建日期?
- algorithm - 链表:删除节点
- rust - 如何将包含特征对象的结构克隆到`Fn`