-1

json code -

"days": [
        {
            "day-code": "SUN", 
            "runs": "Y"
        }, 
        {
            "day-code": "MON", 
            "runs": "Y"
        }, 
        {
            "day-code": "TUE", 
            "runs": "Y"
        }, 
        {
            "day-code": "WED", 
            "runs": "Y"
        }, 
        {
            "day-code": "THU", 
            "runs": "Y"
        }, 
        {
            "day-code": "FRI", 
            "runs": "Y"
        }, 
        {
            "day-code": "SAT", 
            "runs": "Y"
        }
    ] 

for retrieving the "day-code" from PHP by using the following code -

days[0]['day-code'];

OR

days[0][0];

php error -

Fatal error: Uncaught Error: Cannot use object of type stdClass as array

Can anyone help me from this problem.

Anant Kumar Singh
  • 68,309
  • 10
  • 50
  • 94

3 Answers3

0

As per the documentation, you need to specify if you want an associative array instead of an object from json_decode, this would be the code

json_decode($jsondata, true);
Rushil K. Pachchigar
  • 1,175
  • 2
  • 18
  • 38
0

1.json_decode() with parameter true needed.

2.Then you can do like $json_array['days'][0]['day-code'];

Working example:- https://eval.in/776344

you can apply foreach() also(in the working example to print all values one-by-one)

Note:-

The json data you shown is invalid (check here). It missed starting { and closing }

Reference:- http://php.net/manual/en/function.json-decode.php

Anant Kumar Singh
  • 68,309
  • 10
  • 50
  • 94
0

First You need to understand Array and stdClass Object to check this you can use var_dump($var)

your data contain all numeric index. you can can access it by 0,1,2

and single element of array is an object so you can access it by arrow (->)

So it will be like

$days[0]->day-code;
Ankit vadariya
  • 1,187
  • 11
  • 14