使用多维数组/对象解析Json。 PHP

时间:2015-12-12 03:13:20

标签: php json parsing multidimensional-array

我第一次尝试解析JSON文件并将信息插入到我的数据库中。问题是这个对象/数组是多维的,因此$number = stats[0]在数组的每个级别上获取值。 This is a link to the JSON file。我想避免外翻,但我用PHP爆炸了data:值。 Here is a link to my output right now。如果看一下我的输出,我只对8,C,J感兴趣。 Pavelski和26.这些是我想要的数据库中的值。

$json = file_get_contents("http://nhlwc.cdnak.neulion.com/fs1/nhl/league/playerstatsline/20152016/2/SJS/iphone/playerstatsline.json");

$jsonIterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);

foreach ($jsonIterator as $key => $val) {
      $stats = explode(",", $val);

        $number = $stats[0];
        $position = $stats[1];
        $name = $stats[2];
        $gp = $stats[3];
        $goals = $stats[4];
        $assists = $stats[5];
        $points = $stats[6];
        $plsmns = $stats[7];
        $pim = $stats[8];
        $shots = $stats[9];
        $toi = $stats[10];
        $pp = $stats[11];
        $sh = $stats[12];
        $gwg = $stats[13];
        $ot = $stats[14];


        echo $number."    ".$position."    ".$name."    ".$points."<br />";

/* $query = "INSERT INTO stats2015_2016 ('number','position','name','gp','goals','assists','points','plsmns','pim','shots', 'toi', 'pp', 'sh', 'gwg', 'ot')
             VALUES ('$number','$position','$name','$gp','$goals','$assists','$points','$plsmns','$pim','$shots','$toi','$pp','$sh','$gwg','$ot')";
   $result= $db->query($query); */

}

谢谢

1 个答案:

答案 0 :(得分:1)

$json = file_get_contents('http://nhlwc.cdnak.neulion.com/fs1/nhl/league/playerstatsline/20152016/2/SJS/iphone/playerstatsline.json');

$json = json_decode($json, TRUE);

$skaterData = $json['skaterData'];
$goalieData = $json['goalieData'];

foreach($skaterData as $d){
    $sk = explode(',', $d['data']);
    $number = $sk[0];
    $position = $sk[1];
    $name = $sk[2];
    $points = $sk[6];

    echo $number."    ".$position."    ".$name."    ".$points."<br />";
}

根据需要重复守门员数据