PHP and JSON
Wednesday, February 10. 2010
I don´t have alternatives or addition but I wanted to thank you for this.
I read it and implemented it yesterday and I should say that I was impressed! Thank you for the tip!
I also cannot wait for the phpbnl11 to start! It will be great, I am sure!
See you there hopefully!
Don’t forget you can also pass True to the second parameter of json_decode to get back an associative array instead of an object..
I see json_decode() to be pretty useless without setting it’s second parameter to true to obtain an associative array.
What can you do with an stdClass object? Iterate over it? get_class_vars() returns an associative array of what could be built directly by json_decode($str, true).
A stdClass object simply is not really useful, and json_decode() has no way to define using another class like mysqli_fetch_object().
I almost never use json_decode() without true as the second argument either—I find stdClass objects generally pretty useless.
json_encode()‘s JSON_FORCE_OBJECT in 5.3 is useful in dealing with PHP’s array/hash duality:
json_encode(array())
// -> "[]"
json_encode(array(), JSON_FORCE_OBJECT)
// -> "{}"
thanks everyone who mentioned about the object/array flag. Since I was only passing it to print_r it didn’t occur to me to switch it!
Michael: I didn’t know 5.3 was getting that new functionality, thanks for adding your comment :)
Very nice information man, I am just starting my project. This will really help me, thanks a lot


