我试图使用php将多个输入值转换为json数组。
表格:
<input name="title[]">
<input name="description[]">
<input name="total[]">我想要的是:
{"results":
[{"title", "description", "total" }],
[{"title", "description", "total" }],
[{"title", "description", "total" }],
[{"title", "description", "total" }]
}Php代码:
$itemCount = count($_POST["title"]);
$_POST['results'] = [];
for($i=0;$i<$itemCount;$i++) {
if(!empty($_POST["title"][$i]) || !empty($_POST["description"][$i]) || !empty($_POST["total"][$i])) {
$_POST['results'] = json_encode([
[
'title' => cleardata($_POST["title"][$i]),
'description' => cleardata($_POST['description'][$i]),
'total' => cleardata($_POST['total'][$i])
],
]);
}
}
print_r(json_encode($_POST['results']));发布于 2022-11-28 01:42:22
你的表格不清楚。我假设它是一组输入,每个title都与一个description和一个total字段匹配。
另外,您期望的JSON无效。
我们正在使用每个已发布数组中具有相同索引的元素创建新数组。你最终可以把它们投给反对。我们将它们组合到一个全局数组中,并通过编码()将其解析为JSON。
// Since you didn’t indicate form method
$titleData = $_POST['title'] ?? $_GET['title'];
$descriptionData = $_POST['description'] ?? $_GET['description'];
$totalData = $_POST['total'] ?? $_GET['total'];
$results = [];
foreach ($titleData as $count => $result) {
$results[] = [$result, $descriptionData[$count], $totalData[$count]];
// You may cast the added array with (object) if you expect an object
// rather than an array.
}
return json_encode( ["results" => $results] );https://stackoverflow.com/questions/74594864
复制相似问题