【问题标题】:Count entries in a JSON Array?计算 JSON 数组中的条目?
【发布时间】:2013-07-10 01:55:14
【问题描述】:

如何计算从 JSON 中抓取的条目?

下面的示例有 6 个条目,但如您所见.. 如果添加条目,我的代码将忽略它。我可以循环它 10 次,如果它什么也没有,然后停止,但我认为这是一种不好的方式。

是否有任何简单的代码可以在以下 JSON 中提取 6 个“季节”?

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

【问题讨论】:

    标签: php json loops data-extraction


    【解决方案1】:

    foreach 循环可能是您正在寻找的方法。

    例如,无论有多少个季节,此代码都会在您的 JSON 数据中输出每个季节的年份:

    //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;
    }
    

    或者,如果您只需要知道季节数,这将是一个解决方案:

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

    如果需要,您也可以将其与 for 循环结合使用:

    for($i = 0; $i < $numberOfSeasons; $i++) {
        echo $jsonarray['season_history'][$i][0];
    }
    

    【讨论】:

      【解决方案2】:

      没关系..我想通了...这是我使用的代码。

      //Get the page
      $str = file_get_contents('http://myjsonurl.here/');
      $jsonarray = json_decode($str, true);
      
      //FOR EACH SEASON
      foreach ($jsonarray['season_history'] as $var) 
      {
      for ($i = 0; $i <= 15; $i++)
          {
           echo $var[$i];
           //do more stuff here
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-24
        • 2021-07-07
        • 2017-12-01
        • 1970-01-01
        相关资源
        最近更新 更多