I have a HTML Form from which I receive Input, I have a PHP file which posts it to JSON form already. But I need the ID part as identifier of the particular object. I tried all known ways, only ended up with messing up the code. Here's a detail explanation:
JSON Code #1 [Which I'm getting]
[
{
"id": "1",
"name": "aaa",
"doctor": "Doctor #1",
"appointment": "13:03",
"date": "1998-12-15"
},
{
"id": "2",
"name": "bbb",
"doctor": "Doctor #2",
"appointment": "14:14",
"date": "2016-05-31"
}
]
JSON Code #2 [Desired, which I want]
[
"1": { //The ID #1
"name": "aaa",
"doctor": "Doctor #1",
"appointment": "13:03",
"date": "1998-12-15"
},
"2": { //The ID #2
"name": "bbb",
"doctor": "Doctor #2",
"appointment": "14:14",
"date": "2016-05-31"
}
]
This is the PHP code I'm using to post the form data to the JSON File.
$filetxt = 'JSON URL';
$formdata = array(
'id'=> $_POST['id'],
'name'=> $_POST['name'],
'doctor'=> $_POST['doctor'],
'appointment'=> $_POST['appointment'],
'date'=> $_POST['date'],
);
// path and name of the file
$filetxt = 'PATH_OF_THE_FILE';
$arr_data = array(); // to store all form data
if(file_exists($filetxt)) {
$jsondata = file_get_contents($filetxt);
$arr_data = json_decode($jsondata, true);
}
$arr_data[] = $formdata;
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
if(file_put_contents('appointments.json', $jsondata))
include('URL');
else include('URL2');
}
Please help me with the PHP code part. Any way to optimize existing code would be appreciated too. Thanks ^.^
[ "1": {...}, ... ]will be{ "1": {...}, ...}