-1

I know it's been asked many times and I've gone through a good 15 - 20 questions trying to figure out how to get it to work.

JSON

{"menu": {
    "title":"Title One",
    "link":"Link One",
    "title":"Title Two",
    "link":"Link Two"}
}

PHP

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

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

This so far only displays

title: Title Two
link: Link Two

as opposed to

title: Title One
link: Link One
title: Title Two
link: Link Two

Also am I correct in thinking $json_a[menu] does not need apostrophes because $json_a is not a function? it works with or without.

Thanks in advance.

4
  • 6
    You can't have multiple entries with the same key in an array. While JSON might allow it, when it's parsed by PHP, the last definition of the key,value pair wins. It looks like menu should be an array of objects instead. Commented Apr 6, 2014 at 21:28
  • also it will only one key out of multiple in case u do json_decode(). Commented Apr 6, 2014 at 21:29
  • Object properties are unique Commented Apr 6, 2014 at 21:29
  • A little advice: If you're ever unsure of the structure of an object or array, output it with print '<pre>'; print_r($json_a); print '</pre>'; Commented Apr 6, 2014 at 21:35

1 Answer 1

2

You can't have multiple entries with the same key in an array. While JSON might allow it, when it's parsed by PHP, the last definition of the key,value pair wins.

It looks like menu should be an array of objects instead:

{
  "menu": [{
    "title":"Title One",
    "link":"Link One"
  }, {
    "title":"Title Two",
    "link":"Link Two"
  }]
}

PHP

foreach($json_a['menu'] as $value) {
  echo $value['title'] . ": " . $value['link'] . "<br />";
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.