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?

test
  • 17,706
  • 64
  • 171
  • 244
  • 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. – tradyblix Sep 26 '12 at 09:11
  • Your json is not valid and would always return error – Baba Sep 26 '12 at 09:12
  • I know it's not valid. It's longer so I just gave a short snippet. All is well. – test Sep 26 '12 at 10:26
  • A related reference question: [How to extract and access data from JSON with PHP?](https://stackoverflow.com/q/29308898/367456) – hakre Oct 30 '21 at 09:13

1 Answers1

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'];
xdazz
  • 158,678
  • 38
  • 247
  • 274