I'm having an issue with removing an object from a JSON file using PHP.
The code below is supposed to get the current user ID, check to see if that user ID already exists in the JSON file and if it does then delete the old record before writing the new one. If the user ID is unique, the data is supposed to append to the file as a new object (this part works).
Here is my PHP:
//new user id
$user_id = $uvon;
//problem here
$fileContent = file_get_contents($filetxt_1);
$jsonDecode = json_decode($fileContent, true);
foreach($jsonDecode->$user_id as $id)
if (id == "$user_id")
{
unset($user_id);
}
//
//write new object
$myObj=new stdClass();
$myObj->$user_id = new stdClass();
$myObj->$user_id->wallet_address = $walletaddress;
$myObj->$user_id->time_stamp = time();
$myJSON = json_encode($myObj, JSON_UNESCAPEDUNICODE | JSON_UNESCAPED_SLASHES | JSON_NEMERIC_CHECK | JSON_PRETTY_PRINT);
file_put_contents($filetxt_1, $myJSON, FILE_APPEND);
And here is my JSON output.
I nested the information associated with the user ID inside the user ID object, as I thought it would make for easier deletion of ID-related records (search for ID and delete parent object meaning that any children elements would be destroyed too?).
There is only supposed to be one set of data for the user ID, but as you can see, the data is just appending regardless.
{
"77.104.149.212": {
"wallet_address": "0x5895311d3D45FD29b8254b27Da9837478b560290",
"time_stamp": 1521975950
}
}{
"77.104.149.212": {
"wallet_address": "0x5895311d3D45FD29b8254b27Da9837478b560290",
"time_stamp": 1521976301
}
}
Any help is much appreciated. Hopefully, I have explained myself well.
Thanks in advance.