PHP的:从JSON获取元素

时间:2018-07-27 07:40:11

标签: php json

我有JSON输出,如:

from views import NewsView
...
url(r'^news/$', NewsView.as_view()),

我在这里可以阅读日期:

{
date: "26-07-2018",
leagues: [
 {
   league_id: 0,
   league_name: "xxx",
   league_logo: "http://3.bp.blogspot.com/-Eczfs3_ibNw/V5QDDwyxP5I/AAAAAAAAEdM/Jry4L9hzJQwmnWr3Jf1Amy4vzdGfdeeFwCK4B/s60/INT_Champions_Cup_logo.png",
   league_matches: [
          {
            match_id: 1,
            team1logo: "http://1.bp.blogspot.com/-POxAfSSnlW0/UhCt7oQsdLI/AAAAAAAAGDo/rMRXx2mqvUI/s60/Juventus[1].Png",
           team2logo: "http://4.bp.blogspot.com/-8oH--7NYdUI/UgbIXYLMwiI/AAAAAAAAEQo/30KQWgGRJyg/s60/Bayern+Munchen+(2).png",
           match_time: "23:00",
           channels_id: [
                         1
                        ],
          team1: "xxx",
          team2: "xxx"
         },
        {
         match_id: 2,
         team1logo: "http://1.bp.blogspot.com/-86nRbJxtZ_o/UgbePFW0WEI/AAAAAAAAFFw/R6Gvxeyt1gQ/s60/Manchester+City+(2).png",
         team2logo: "http://3.bp.blogspot.com/-D0lb4b-qN5U/UgbeDosqjYI/AAAAAAAAFBY/Qg7kvoodvFY/s60/Liverpool+(2).png",
         match_time: "00:00",
         channels_id: [
                       2
                      ],
         team1: "xxx",
         team2: "xxx"
        }
      ]
    }
  ]
}

但是我需要阅读Leagues以及League_name和team1 .....的所有元素。

如何获取?

我可以使用json_decode解析每个值以进行进一步的数据处理吗?

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以尝试类似

   $obj = json_decode($json, true);
   echo $obj['leagues']['league_name'];
   foreach($obj['leagues']['league_matches'] as $matches) {
       echo $matches['team1'];
   }    

答案 1 :(得分:0)

实际上,您的json响应包含Date在数组ObjectLeage Name中,而league_matchesarray of object

 echo 'Date: '.$obj->date.'<br/>';
            $leagues = $obj->leagues;
            echo 'Leage Name: '.$leagues[0]->league_name.'<br/>';
           $team1 = '';
           foreach($leagues[0]->league_matches as $matches) {
          $team1 =$team1.','.$matches->team1;
          echo 'Team1: '.$matches->team1.'<br/>';
       }
//after concatenation of team1 with comma
echo 'Team1: '.ltrim($team1,',').'<br/>';

输出:

    Date: 26-07-2018
    Leage Name: xxx
    Team1: xxx
    Team1: xxx 
//after concatenation of team1 with comma
    Team1: xxx,xxx