Reputation: 998
I'm trying to use json_decode to get "short_name" from with the "universities" section of the code attached at the bottom of this post - it's from Coursera (online course website).
I first do:
$Course= json_decode(file_get_contents(COURSES_URL), true);
Then I have no problem getting the top-level data such as "id" by doing:
$CourseId = $Course['id'];
But when it comes to within the "universities" array, I cant access any data, I keep getting "Undefined index: short_name" I have tried all sorts, such as:
$university= $Course['universities']['short_name'];
But I am getting nowhere now...How do you access this data ?
Coursera JSON:
[
{
"subtitle_languages_csv":"",
"photo":"https://s3.amazonaws.com/coursera/topics/ml/large-icon.png",
"preview_link":"https://class.coursera.org/ml/lecture/preview",
"small_icon_hover":"https://s3.amazonaws.com/coursera/topics/ml/small-icon.hover.png",
"large_icon":"https://s3.amazonaws.com/coursera/topics/ml/large-icon.png",
"video":"e0WKJLovaZg",
"university-ids":[
"stanford"
],
"id":2,
"universities":[
{
"rectangular_logo_svg":"",
"wordmark":null,
"website_twitter":"",
"china_mirror":2,
"favicon":"https://coursera-university-assets.s3.amazonaws.com/dc/581cda352d067023dcdcc0d9efd36e/favicon-stanford.ico",
"website_facebook":"",
"logo":"https://coursera-university-assets.s3.amazonaws.com/d8/4c69670e0826e42c6cd80b4a02b9a2/stanford.png",
"background_color":"",
"id":1,
"location_city":"Palo Alto",
"location_country":"US",
"location_lat":37.44188340000000000,
"location":"Palo Alto, CA, United States",
"primary_color":"#8c1515",
"abbr_name":"Stanford",
"website":"",
"description":"The Leland Stanford Junior University, commonly referred to as Stanford University or Stanford, is an American private research university located in Stanford, California on an 8,180-acre (3,310 ha) campus near Palo Alto, California, United States.",
"short_name":"stanford",
"landing_page_banner":"",
"mailing_list_id":null,
"website_youtube":"",
"partner_type":1,
"banner":"",
"location_state":"CA",
"name":"Stanford University",
"square_logo":"",
"square_logo_source":"",
"square_logo_svg":"",
"location_lng":-122.14301949999998000,
"home_link":"http://online.stanford.edu/",
"class_logo":"https://coursera-university-assets.s3.amazonaws.com/21/9a0294e2bf773901afbfcb5ef47d97/Stanford_Coursera-200x48_RedText_BG.png",
"display":true
}
],
Upvotes: 0
Views: 184
Reputation: 29462
universities
is one element array, so use 0 index before getting to university property:
$university= $courseraCourse['universities'][0]['short_name'];
If returned JSON contains more than one university, you can loop through it:
foreach($courseraCourse['universities'] as $university) {
echo $university['short_name'] . '<br>' ;
}
Upvotes: 1