Reputation: 116
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?
Upvotes: 0
Views: 44
Reputation: 20469
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
Upvotes: 1
Reputation: 2302
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} ?>
Upvotes: 1