3

Let's say I have this JSON:

{
  "achievement": [
    {
      "title": "Ready for Work",
      "description": "Sign up and get validated",
      "xp": 50,
      "difficulty": 1,
      "level_req": 1
    },
    {
      "title": "All Around Submitter",
      "description": "Get one piece of textual content approved in all five areas.",
      "xp": 500,
      "difficulty": 2,
      "level_req": 1
    }
}

and I am trying this thru PHP:

$string = file_get_contents("achievements.json");
$json_a=json_decode($string,true);

$getit = $json_a->achievement['title'][1];

I'm trying to get the first "id" of the achievement.. which would be READY FOR WORK.

How do I fix this?

4
  • just to mention, there's a missing ] before the last }, cause the one you posted isn't valid until that missing square bracket is added. Commented Sep 26, 2012 at 9:11
  • Your json is not valid and would always return error Commented Sep 26, 2012 at 9:12
  • I know it's not valid. It's longer so I just gave a short snippet. All is well. Commented Sep 26, 2012 at 10:26
  • A related reference question: How to extract and access data from JSON with PHP? Commented Oct 30, 2021 at 9:13

1 Answer 1

9

When you set the second parameter of json_decode to true, it will return an array.

$json_a=json_decode($string,true);

returns an array.

$getit = $json_a['achievement'][1]['title'];
Sign up to request clarification or add additional context in comments.

3 Comments

And change the index from 1 to zero to get the Ready for Work item. After all, arrays in PHP are are zero based indexed.
Ah, right, I am so silly to be like.. what. Thanks. So.. the IDs start from 0.
@weka Yes, 1 means second element of $json_a['achievement'].

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.