我在php文件中嵌入了一个json文件,我想从json文件中的表单添加新信息...
我的表单是
<form action="process.php" method="POST">
First name:<br>
<input type="text" name="firstName">
<br><br/>
Last name:<br>
<input type="text" name="lastName">
<br><br>
Email:<br>
<input type="text" name="email">
<br><br>
Mobile:<br>
<input type="text" name="mobile">
<br><br>
<input type="submit" value="Submit">
</form>
并且php文件是
<?php
$myFile = "data.php";
$arr_data = array(); // create empty array
try
{
//Get form data
$formdata = array(
'firstName'=> $_POST['firstName'],
'lastName'=> $_POST['lastName'],
'email'=>$_POST['email'],
'mobile'=> $_POST['mobile']
);
//Get data from existing json file
$jsondata = file_get_contents($myFile);
// converts json data into array
$arr_data = json_decode($jsondata, true);
// Push user data to array
array_push($arr_data,$formdata);
//Convert updated array to JSON
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
//write json data into data.json file
if(file_put_contents($myFile, $jsondata)) {
echo 'Data successfully saved';
}
else
echo "error";
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
当我单击“提交”按钮时,将按如下所示添加新数据
{
"heroes": [
{
"firstName": "Vijay",
"lastName": "reddy",
"email": "asdv@ymail.com",
"mobile": ""
},
{
"firstName": "Paki",
"lastName": "Webb",
"email": "vahodid@yahoo.com",
"mobile": "66464646464"
},
{
"firstName": "sagar",
"lastName": "rawal",
"email": "searchbbc1881@gmail.com",
"mobile": "98989898"
}
],
"0": {
"firstName": "sagar",
"lastName": "rawal",
"email": "searchbbc1881@gmail.com",
"mobile": "98989898"
},
"1": {
"firstName": "Purnima",
"lastName": "rawal",
"email": "searchbbc1881@gmail.com",
"mobile": "98652845"
}
}
但是我想将数据作为
{
"heroes": [
{
"firstName": "Vijay",
"lastName": "reddy",
"email": "asdv@ymail.com",
"mobile": ""
},
{
"firstName": "Paki",
"lastName": "Webb",
"email": "vahodid@yahoo.com",
"mobile": "66464646464"
},
{
"firstName": "sagar",
"lastName": "rawal",
"email": "searchbbc1881@gmail.com",
"mobile": "98989898"
},
{
"firstName": "sagar",
"lastName": "rawal",
"email": "searchbbc1881@gmail.com",
"mobile": "98989898"
},
{
"firstName": "Purnima",
"lastName": "rawal",
"email": "searchbbc1881@gmail.com",
"mobile": "98652845"
}
]
}
即删除索引并将新数据与其他数据一起写入json内...到目前为止我做不到...所以请帮助我...
答案 0 :(得分:2)
您只是对整个json数组执行了array_push,您希望将其放入“英雄”中
// converts json data into array
$arr_data = json_decode($jsondata, true);
$arr_data['heroes'][] = $formdata; // Will push $formdata inside 'heroes' array from json
如果您更喜欢使用array_push,请执行以下操作:
// converts json data into array
$arr_data = json_decode($jsondata, true);
array_push($arr_data['heroes'], $formdata); // Will push $formdata inside 'heroes' array from json
答案 1 :(得分:0)
更改此
array_push($arr_data,$formdata)
对此
array_push($arr_data['heroes'],$formdata)