0

I have a classic JSON problem, and i know that many post are asking about that... But i doubt that the JSON i try to grab has a correct structure.

The files Begin like that :

[{
"time":"0-12h",
"articles":[
{
"id":1,
"domain_id":22,
"title":"Hi Guys"
 }

{
"id":2,
"domain_id":17,
"title":"Hi everyone"
 }

]

}]

I have try a lot of combinaison to echo the title :

$data = json_decode($json, true);
echo $data->articles;    

Or

echo $data->articles->title;

Or

echo $data->articles[0]->title;

Nothing works... :( Can you help me ? Thanks !

3
  • If the file really looks like that, then it's invalid JSON. It's missing a comma between the } ending one object and the `{ starting the next in an array. Commented Jun 24, 2013 at 15:51
  • Invalid JSON to start with Commented Jun 24, 2013 at 15:52
  • 1
    @ØHankyPankyØ: No, other than the missing comma, it's fine. Commented Jun 24, 2013 at 15:56

3 Answers 3

1

The second argument true to json_decode() means it should create associative arrays rather than objects for {} in the JSON. So in addition to dealing with the indexed arrays as Explosion Pills points out, you also need to use array syntax to access the keyed elements:

$data[0]['articles'][0]['title']

If you want to be able to use -> syntax, leave out the second argument or set it to false.

I'm hoping the missing comma in the JSON is an error when transcribing to the question. If not, you also need to fix the code that creates the JSON in the first place.

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

1 Comment

Thanks, it perfect ! You are right, the missing comma is my mistake. Many thanks for your solution :)
0

$data itself is an array. Try

$data[0]->articles[0]->title;

Also the JSON is not valid (missing a comma before the second articles array element).

1 Comment

As @Barmar mentionned in his answer, the second argument of the json_decode method creates an array, not an object.
0

there is a comma , missing

}
,
{

json_decode with the second parameter true returns an array

print_r($data['articles']);

echo $data['articles'] would output Array

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.