无法从JSON数组中获取数据

时间:2013-11-27 06:37:17

标签: php arrays json

尝试学习JSON。做一些简单的练习,但无法通过这一个。我已经重新编写了30次这个教程。有什么指针吗?

这是JSON:

{
  "name": "Username",
  "profile_name": "profile_username",
  "profile_url": "http://myapi.net/profile_username"
  "courses": [
    { "name": "English 340" },
    { "name": "History 202" },
    { "name": "Underwater Basket Weaving" }
  ]
}

它位于一个名为$ JSON_array的变量中,这是我试图用来拉出课程名称然后放在无序列表中的foreach循环。

<ul>
  <?php for( $i = 0; $i < count($JSON_array->courses); $i++ ): ?>
    echo '<li>';
    echo $JSON_array->{'courses'}[$i]->{'name'};
    echo '</li>';  
  <?php endfor; ?>
</ul>

没有做任何事......我的源代码显示空列表项

3 个答案:

答案 0 :(得分:1)

试试这个:

$json = '{"name": "Username","profile_name": "profile_username","profile_url": "http://myapi.net/profile_username",
"courses": [
    { "name": "English 340" },
    { "name": "History 202" },
    { "name": "Underwater Basket Weaving" }
  ]
}';//comma was missing after profile_url

$arr = json_decode($json,true);//encode as an associative array

<ul>
 <?php
  foreach($arr['courses'] as $course){
    echo '<li>';
    echo $course['name'];
    echo '</li>';  
  }
 ?>
</ul>

答案 1 :(得分:0)

试试这个

<ul>
    <?php foreach($JSON_array->courses as $course): ?>
        echo '<li>';
        echo $course->name;
        echo '</li>';  
    <?php endforeach; ?>
</ul>

更新: 而且,你的JSON无效! "profile_url": "http://myapi.net/profile_username" 你在这一行的末尾错过了逗号

答案 2 :(得分:0)

您在profile_url

之后缺少,
$json = '{
  "name": "Username",
  "profile_name": "profile_username",
  "profile_url": "http://myapi.net/profile_username",
  "courses": [
    { "name": "English 340" },
    { "name": "History 202" },
    { "name": "Underwater Basket Weaving" }
  ]
}';



$arr = json_decode($json);
?>

<ul>
  <?php for( $i = 0; $i < count($arr->courses); $i++ ): 
    echo '<li>';
    echo $arr->{'courses'}[$i]->{'name'};
    echo '</li>';  
  endfor; ?>
</ul>