0

我正在尝试使用 json_decode 从本文底部附加的代码的“大学”部分中获取“short_name”——它来自 Coursera(在线课程网站)。

我首先这样做:

$Course= json_decode(file_get_contents(COURSES_URL), true);

然后我可以通过执行以下操作来获取诸如“id”之类的顶级数据:

$CourseId = $Course['id'];

但是当涉及到“大学”数组时,我无法访问任何数据,我不断收到“未定义的索引:短名称”,我尝试了各种方法,例如:

$university= $Course['universities']['short_name'];

但我现在无处可去......你如何访问这些数据?

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
}
],
4

1 回答 1

1

universities是一个元素数组,因此在获取大学属性之前使用 0 索引:

$university= $courseraCourse['universities'][0]['short_name'];

如果返回的 JSON 包含不止一所大学,您可以循环遍历它:

foreach($courseraCourse['universities'] as $university) {
    echo $university['short_name'] . '<br>' ;
}
于 2013-09-13T21:49:33.823 回答