0

JSON

{
 "pages":{
   "index.php":{
      "status":"enabled",
      "theme":"dark",
      "identifier":"KMS"
  },
   "google.php":{
      "status":"enabled",
      "theme":"dark",
      "identifier":"KMS"
  },
   "doodle.php":{
      "status":"disabled",
      "theme":"light",
      "identifier":"transact"
   }
 }
}

In my PHP code I write

$jsona = file_get_contents("../pages.json");
$jsonb = json_decode($jsona,true);  
$data = $jsonb['pages'];

Now if I want to delete the property "index.php" I write unset($data["index.php"] and then I write

file_put_contents("../pages.json",json_encode($data));

Though after going to my JSON file it deletes "pages"

actual outcome

{"google.php":{"status":"enabled","theme":"dark","identifier":"KMS"},"doodle.php":{"status":"disabled","theme":"light","identifier":"transact"}}

I need to just unset a specific child property of pages. Such as "google.php" or "doodle.php". I checked what is being posted as $data[$page] and it is the specific element. So why is it unsetting pages and leaving the rest of the properties?

1
  • It's not unsetting pages, you're just not serializing that part... Try json_encode(array("pages"=>$data)) Commented Jul 21, 2014 at 4:18

1 Answer 1

2

Don't set $data to $jsonb['pages']. That's specifically setting your $data variable to a sub-section of your overall object.

Just use unset($jsonb['pages']['index.php']).

Sign up to request clarification or add additional context in comments.

4 Comments

Ok I'll try that out.
Alrighty so that worked. Why did setting $data = $jsonb['pages'] mess it up?
Because you were "cropping" away the outer-most object. If I have x = { a: 'b'}, and use y = x['a'], y has lost the outer-most object, and is now just the string 'b'.
Ah ok. Well that explains it :D Thanks Meagar!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.