0

I have the folowing format of json:

[
    {
        "title": "title will be here",
        "teaser": "teaser will be here...",
        "date": ["2015-11-19T00:00:00"]
   }
]

and the php to read the json:

$json = file_get_contents( "news.json" );
$data = json_decode( $json );
json_decode( json_encode( $data ), true );

foreach ( $data as $object ):
    echo $object->{'title'};
    echo $object->{'teaser'};
    echo $object->{'date'};
endforeach;

the code returns title and teaser but not the date, what should i do to return the date correctly?

2
  • The date value is an array; you should see a warning cannot convert Array to string. Commented Nov 20, 2015 at 14:50
  • why decode/encode/decode again? Why not just a single $data = json_decode($json, true)? and 'date' is an array. you can't echo out an array. $object->date[0], maybe. Commented Nov 20, 2015 at 14:53

2 Answers 2

1

your date is in an array so $object->date will return an array. you may only what the first key of the array

date: <?= reset($object->date); ?>

or output all

date: <?php foreach($object->date as $date){echo $date} ?>
Sign up to request clarification or add additional context in comments.

Comments

1

The date property is an array. If it only contains 1 valuu, or you only ever want the 1st value, simply access the 1st element:

$json=file_get_contents("news.json");
$data =  json_decode($json);
foreach($data as $object):
    echo $object->title;
    echo $object->teaser;
    echo $object->date[0];
endforeach;

If you may want to access multiple date values, iterate the array:

foreach($data as $object){
    echo $object->title;
    echo $object->teaser;
    foreach($object->date as $date){
        echo $date;
    }
}

Note i also removed the erroneous json_decode(json_encode($data), true); line and simplified your property access code - all the names are valid property names so no need for the {'...'} syntax

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.