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": "chandlerbing@centralperk.com", "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:
{ "chandlerbing@centralperk.com" { "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);
Advertisement
Answer
If Email
is the attribute to uniquely identify a user. It would be great to keep this as key
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
{ "chandlerbing@centralperk.com" : [ { "ExerciseType": "Running", "DistanceTravelled": "35", }, { "ExerciseType": "Jogging", "DistanceTravelled": "13", }, ], "test@centralperk.com" : [ { "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));