如何解决$_POST 中每个循环的 PHP
我正在创建一个可共享的表单并使用 JSON 作为结构。当有人要提交表单上的数据时,我就卡住了。
{
"table-name": "Locations-Grid view(1)","created-on": "May 13,2021","token": "nKdcXx2d0bbLifg","columns": "Locations,Lat,Lng","data": [
{
"Locations": "Mumbai 1","Lat": "19.088008","Lng": "72.882959"
},{
"Locations": "Mumbai 2",{
"Locations": "Mumbai 3",{
"Locations": "Mumbai 4",{
"Locations": "Mumbai 5",{
"Locations": "Mumbai 6",{
"Lng": "45254"
},{
"Lng": "455"
}
]
}
正如您所看到的,最后 2 项 没有存储“位置”和“纬度”,并且仍然只有“Lng”。这里我使用 PHP 在我的输入元素上做的,在检查每个输入名称后,它成功打印在 html 上,你可以看到我使用元素名称,与我的 JSON 中的列完全相同
$jsn = file_get_contents('tables/test.json');
$arr = json_decode($jsn,true);
$data = $arr["columns"];
$pars = explode(',',$data);
//create DOM inputs according to each columns in my array
foreach ($pars as $value) {
$DOM .= '<div class="relative md:w-full lg:w-full mr-30 popup">
<label for="hero-field" class="leading-7 text-sm text-gray-600"> <span>'.$value.'</span</label>
<input type="text" name="'.$value.'" class="w-full bg-gray-100 rounded border bg-opacity-50 border-gray-300 focus:ring-2 focus:ring-indigo-200 focus:bg-transparent focus:border-indigo-500 text-base outline-none text-gray-700 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out" value="" required>
</div>';
}
这就是它在我的 html 中的样子。和工作
<form class="w-full" method="POST" action="<?PHP echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"style="margin-left:40px;">
<?PHP echo $DOM; ?>
<button type="submit" class="inline-flex text-white bg-indigo-500 border-0 py-2 px-6 focus:outline-none hover:bg-indigo-600 rounded text-lg">Submit form</button>
</form>
问题是使用 POST 方法提交时,它保存在 JSON 上,但只保存了“Lng”。这是我所做的
$data1 = $arr["data"];
$data = $arr["columns"];
$pars = explode(',$data);
foreach ($pars as $value) {
$temp = array( $value => $_POST[$value],);
}
//sending it
array_push($data1,$temp);
$arr["data"] =$data1
if(file_put_contents('tables/test.json',json_encode($arr,JSON_PRETTY_PRINT))){
echo 'submitted';
}else{
echo 'Failed';
}
解决方法
这个循环每次循环都会覆盖 $temp
,因此你只能从数组中获得最后一次出现
foreach ($pars as $value) {
$temp = array( $value => $_POST[$value],);
}
改为做
foreach ($pars as $value) {
$temp[$value] = $_POST[$value];
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。