-3

I have the following code:

$json = ' {
    "HTML": 
        [
            {
              "id": 1,
              "name": "HTML",
              "match": false
            },
            {
              "id": 2,
              "name": "HTML 5",
              "match": false
            },
            {
              "id": 3,
              "name": "XHTML",
              "match": false
            }
        ]
}';

$obj = json_decode($json);
$obj[0][0]->name; // JavaScript: The Definitive Guide

Why do I get the following error?

use object of type stdClass as array

I decode the json correctly, than I say that I want to pick the first object from the array (in this case HTML) and than I want to pick the name of the first one in the array.

What is going wrong?

Jeroen
  • 91
  • 1
  • 11
  • 1
    The first level of data isn't a JSON array, it's a JSON object, so PHP decodes it to an instance of `stdClass`. Next, the first level of the data is 'HTML', not '0'. Finally, if you want to force the decode to set everything as arrays, set the second arg to `true` on your `json_decode`. – Jonnix Jun 10 '16 at 12:46
  • The first thing is an object and inside the property `HTML` is your array, which you want to access then with `[0]->name` – Rizier123 Jun 10 '16 at 12:46

1 Answers1

1

Your first JSON is object (HTML), which contains an array of another objects. You must call ->HTML[0] (which is first object in your array) and then ->name, which is parameter of your HTML object.

$obj->HTML[0]->name;
pes502
  • 1,597
  • 3
  • 17
  • 32