1

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.

  • When you pass `true` as second parameter to `json_decode`, the objects are returned as associative arrays. –  Mar 25 '18 at 11:49
  • It's irrelevant that the data is stored in a JSON file, so your question boils down to "How do I remove duplicates?". Using that search term, it should be pretty easy to find solutions, but seriously, if you had a hand of cards, how would you remove duplicates? Shouldn't be too difficult, so I don't get what your problem is. BTW: Provide a [mcve] if you really have a programming problem. – Ulrich Eckhardt Mar 25 '18 at 11:54
  • @UlrichEckhardt Apologies, I'm quite new to this. Thanks to your advice, I've just learned about the array_unique() function. I think that puts me on the right lines. I will have a play around. – Charles Raiser Mar 25 '18 at 12:05

0 Answers0