2

I'm working with .json files and I have the following function:

//Rights array (WRITE, CREATE, DELETE, ADDUSERS, DELETE USERS)
function addUser($requester, $username, $rights) {
    $file = $requester->getFolder() . "Projects/" . $this->name . "/Data/users.json";
    $json = json_decode(file_get_contents($file, false));
    $json[$username] = array("write" => $rights[0], "create" => $rights[1], "delete" => $rights[2], "adduser" => $rights[3], "deleteuser" => $rights[4]);
    file_put_contents($file, json_encode($json));
}   

Whenever I run the code that uses that function, I get the following error:

Fatal error: Cannot use object of type stdClass as array in...

1
  • It would be nice to show us the whole error with content of the line. Commented Apr 27, 2015 at 23:14

1 Answer 1

2

The second parameter of json_decode defaults to false, meaning it will produce an object. Use true to produce an array.

The error comes from $json[$username] where you are accessing $json as an array. When it is an object, you would access it like: $json->$username.

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

8 Comments

I thought it was the other way around... I should've checked :P Thanks man!
I'm still getting the error. I kept everything the same except: '$json = json_decode(file_get_contents($file, true));' And the error is on this line (39): '$json[$username] = array("write" => $rights[0], "create" => $rights[1], "delete" => $rights[2], "adduser" => $rights[3], "deleteuser" => $rights[4]);'
Youre using true on file_get_contents, not json_decode.
Now I've got two errors after I updated with that code: 'Warning: Illegal string offset 'adad' in D:\xampp\htdocs\Collabs\Examples\Project\Scripts\Classes\Project.php on line 39' ------ 'Notice: Array to string conversion in D:\xampp\htdocs\Collabs\Examples\Project\Scripts\Classes\Project.php on line 39'
Search for those error messages, look into your line number, and try to figure out what the error message is telling you. You'll eventually need to figure out how to resolve debugging on your own.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.