We get a strange error using json_decode(). It decode correctly the data, but when we try to access info inside the array we get the following:
We tried to do: $result[‘context’] where $result has the data returned by json_decode()
php json
The function json_decode() returns an object by default.
Access the data :
If we have identifiers like from-date (the hyphen would cause a PHP error when using the above method) we have to write the following:
- If we have identifiers like from-date (the hyphen would cause a PHP error when using the above method) we have to write the following:
- If we need an array we can do the following:
- Or cast the object to an array:
- Use the second parameter of json_decode to make it return an array:
- Use true as the second parameter to json_decode.
- This will decode the json into an associative array instead of stdObject instances:
- If we call json_decode($somestring) we will get an Object and we need to access like $object->key,
- But if we call json_decode($somestring, true) we will get an array and can access like $array[‘key’]
We can convert stdClass object to array :
[ad type=”banner”]function:
- When param is false, which is default, it will return an appropriate php type.
- When param is true, it will return associative arrays.
- It will return NULL on error.
- If we want to fetch value through array, set assoc to true.
we must access it using -> since its an object.
Change our code from:
To:
- print_r — Prints human-readable information about a variable
- When we use json_decode();, we get an object of type stdClass as return type.
- The arguments, which are to be passed inside of print_r() should either be an array or a string. Hence, we cannot pass an object inside of print_r(). There are two ways to deal with this.
1. Cast the object to array.
This can be achieved as follows.
2. By accessing the key of the Object
when we use json_decode(); function, it returns an Object of stdClass. we can access the elements of the object with the help of -> Operator.
- Use multiple keys to extract the sub elements incase if the object has nested arrays.
Their are many options to print_r() like var_dump(); and var_export();
[ad type=”banner”]