drmticpet66231422 2013-07-10 01:55
浏览 36
已采纳

计算JSON数组中的条目?

How do I count the entries I am scraping from JSON?

The below example has 6 entries, but as you can see.. if an entry is added, my code will ignore it. I could loop it 10 times and if it picks up nothing, then stop, but I think that's a bad way of doing it.

Is there any simple code that picks up 6 'seasons' in the following JSON?

MYPAGE.PHP

//Get the page
$str = file_get_contents('http://myjsonurl.here/');
$jsonarray = json_decode($str, true);

$season1 = $jsonarray['season_history'][0][0];
$season2 = $jsonarray['season_history'][1][0];
$season3 = $jsonarray['season_history'][2][0];
$season4 = $jsonarray['season_history'][3][0];
$season5 = $jsonarray['season_history'][4][0];
$season6 = $jsonarray['season_history'][5][0];
//the rest of the info here..

JSON

{
    "season_history": [
        ["2006/07", 2715, 12, 11, 0, 45, 0, 0, 0, 1, 0, 0, 26, 0, 91, 169],
        ["2007/08", 2989, 15, 11, 0, 56, 0, 0, 0, 3, 0, 0, 18, 0, 95, 177],
        ["2008/09", 2564, 9, 10, 0, 20, 0, 0, 0, 2, 0, 0, 14, 0, 95, 138],
        ["2009/10", 2094, 12, 6, 0, 13, 0, 0, 0, 1, 0, 0, 8, 0, 92, 130],
        ["2010/11", 2208, 21, 4, 8, 28, 0, 0, 0, 1, 0, 0, 26, 0, 92, 176],
        ["2011/12", 521, 7, 0, 2, 6, 0, 0, 0, 0, 0, 0, 5, 146, 89, 49]
    ]
}
  • 写回答

2条回答 默认 最新

  • doulie0178 2013-07-10 02:29
    关注

    A foreach loop may be the approach you're looking for.

    For example, this code would output the years for each season in your JSON data, regardless of how many seasons there were:

    //Get the page
    $str = file_get_contents('http://myjsonurl.here/');
    $jsonarray = json_decode($str, true);
    
    foreach($jsonarray['season_history'] as $season) {
        echo $season[0] . PHP_EOL;
    }
    

    Alternatively, if you just need to know the number of seasons, this would be a solution:

    //Get the page
    $str = file_get_contents('http://myjsonurl.here/');
    $jsonarray = json_decode($str, true);
    
    $numberOfSeasons = count($jsonarray['season_history']);
    

    You could combine that with a for loop as well, if you wanted:

    for($i = 0; $i < $numberOfSeasons; $i++) {
        echo $jsonarray['season_history'][$i][0];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。