2

Let's say my JSON is this:

{
  "achievement": [
    {
      "title": "All Around Submitter",
      "description": "Get one piece of content approved in all six areas.",
      "xp": 500,
      "level_req": 1
    },
    {
      "title": "World-wide Photo Journalist",
      "description": "Get one photo approved in all six areas.",
      "xp": 500,
      "level_req": 1
    },
    {
      "title": "Ready for Work",
      "description": "Sign up and get validated",
      "xp": 50,
      "level_req": 1
    },
    {
      "title": "Asian Pride",
      "description": "Get ten pieces of content approved to a club in an Asian nation.",
      "xp": 1500,
      "level_req": 1
    }
  ]
}

and my PHP code is this, so I load through that json file...:

<?php

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

foreach ($json_a as $key => $value){
  echo  $value[0]['title'] . " <br />";
}

?>

However it only out puts the first array. I know. Only 1. But what about the foreach loop? Why isn't it loop for each row?

1
  • The outer associative array has only one item: achievement. That’s why there is only one iteration. Commented Sep 16, 2012 at 22:23

3 Answers 3

7

You're looping over the top level array, which only has one key: achievement

Instead, you should

foreach ($json_a['achievement'] as $key => $value){
  echo  $value['title'] . " <br />";
}

Hint: [0] is a certain code smell.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I get it now. Top-level array, it was.
1

Here try this

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

foreach ($json_a['achievement'] as $key => $value){
  echo  $value['title'] . " <br />";
}

Your were looping your top array, but after you parse your json you get:

array(1) {
  ["achievement"]=>
  array(4) {
  //your other arrays
  }
}

Comments

0

It isn't working because the array you are looping through only has one key, achievements, this is the array returned by your json_decode(), given your current json. Loop through that, and you'll get what you're after:

foreach ($json_a['achievement'] as $key => $value){
    echo $value['title'] . "<br />";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.