0

JSON からスクレイピングしているエントリをカウントするにはどうすればよいですか?

以下の例には 6 つのエントリがありますが、ご覧のとおり、エントリが追加された場合、私のコードはそれを無視します。10回ループして、何も拾わない場合は停止することもできますが、それは悪い方法だと思います.

次の JSON で 6 つの「季節」を取得する簡単なコードはありますか?

マイページ.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]
    ]
}
4

2 に答える 2

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];
}
于 2013-07-10T02:29:03.700 に答える