php - Saving multiple data for a user JSON array

For a site I'm working on, a user has the option to input exercise data and it is saved to a JSON file in an array:
{
"Email": "[email protected]",
"ExerciseType": "Running",
"DistanceTravelled": "35",
},
But what I want it to do is to be able to save it in a multidimensional array so multiple records can be put in for one user.
Example:
{
"[email protected]"
{
"ExerciseType": "Running",
"DistanceTravelled": "35",
}
}
That way multiple records for the user are saved under one primary object to make it easier to access later. However I've never used multi-dimensional arrays before so I can't figure out how to modify my code to get this to work.
// Save data
$file = ('data.json');
$arr = array();
$new_userstats = array (
'Email' => $email,
'ExerciseType' => $exerciseType,
'DistanceTravelled' => $distance
);
$jsondata = file_get_contents($file);
$arr_data = json_decode($jsondata, true);
array_push($arr_data, $new_userstats);
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file,$jsondata);
Answer
Solution:
IfEmail
is the attribute to uniquely identify a user. It would be great to keep this askey
of our array to easily find
and add a new data to existing file.
Now the format we would be storing in file looks like
{
"[email protected]" : [
{
"ExerciseType": "Running",
"DistanceTravelled": "35",
},
{
"ExerciseType": "Jogging",
"DistanceTravelled": "13",
},
],
"[email protected]" : [
{
"ExerciseType": "Running",
"DistanceTravelled": "11",
},
]
}
Now how to add new data to this file would be in following way.
// Fetch existing data
$strFile = 'data.json';
$arrExistingData = json_decode(file_get_contents($strFile), true);
// Add new data to existing data, new data would contain and object in following way
$arrNewData = [
'ExerciseType' => $exerciseType,
'DistanceTravelled' => $distance
];
$arrExistingData[$email][] = $arrNewData;
// Save data back to file, avoid JSON_PRETTY_PRINT to reduce the file size.
file_put_contents($strFile, json_encode($arrExistingData));
Answer
Solution:
Try:
$new_userstats = array (
$email => array (
'ExerciseType' => $exerciseType,
'DistanceTravelled' => $distance
)
);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: your system folder path does not appear to be set correctly. please open the following file and correct this: index.php
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.