dongyi1111
2014-06-11 10:38
浏览 196

使用PHP从JSON解析多维数组

I need to take data from an external JSON file and parse with PHP into MySQL.

Getting very frustrating and been working on it for hours but I am just failing to be able to do it and I would really appreciate the help.

I can INSERT the data to MYSQL myself but I need help please in preparing it.

Example of how the external JSON file structure looks.

[
  {
    league_id: "3",
    league_name: "League "3",
    teams: []
  },

  {
    league_id: "2",
    league_name: "League 2",
    team: [
      {
        name_of_team: "Brixton United",
        number_of_players: "28",
        homeground: "Brockewell Park",
        history: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.",
        nextmatchtime: 1405046700
      }
      ]
      },

     {
    league_id: "1",
    league_name: "League 1",
    team: [
      {
        name_of_team: "Croydon Crusaders",
        number_of_players: "26",
        homeground: "North End Road",
        history: "Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum.",
        nextmatchtime: 1402458300
      },
      {
        name_of_team: "Streatham Skaters",
        number_of_players: "31",
        homeground: "Streatham Common",
        history: "Curabitur sit amet mauris. Morbi in dui quis est pulvinar ullamcorper. Nulla facilisi. Integer lacinia sollicitudin massa. Cras metus. Sed aliquet risus a tortor. Integer id quam. Morbi mi. Quisque nisl felis, venenatis tristique, dignissim in, ultrices sit amet, augue. Proin sodales libero eget ante. Nulla quam. Aenean laoreet. Vestibulum nisi lectus, commodo ac, facilisis ac, ultricies eu, pede. Ut orci risus, accumsan porttitor, cursus quis, aliquet eget, justo.",
        nextmatchtime: 1433990700
      }
     ]
      }
      ]

I am stuck with the PHP and trying to echo it out to test the script output so I can insert it in to MYSQL later.

It is essential that the nested inner arrays inherit the outer arrays Keys/value as there will not be any outer (leagues) arrays inserted. Only the inner arrays (teams) will be inserted.

    <?php

        //create a DB connection
        $con=mysqli_connect("localhost","wordpress1","*****","wordpress1");


        $my_arr = file_get_contents("http://example.com/updating/json/data.php");
        $ujson = json_decode($my_arr, true);




   // Inner array and outer array inherited fields, to be inserted in to MYSQL later.

      foreach ($ujson as $key => $value)
        {


    if (is_array($value))
  foreach ($value as $key2 => $value2)
    {
                    echo $value['name_of_team'];
            echo "</br>";

            echo $value['number_of_players'];
            echo "</br>";

                    echo $value['homeground'];
            echo "</br>";

            echo $value['history'];
            echo "</br>";

                    echo $value['nextmatchtime'];
            echo "</br>";

   }
  else
   {
                    echo $value['league_id'];
            echo "</br>";

            echo $value['league_name'];
            echo "</br>";

   }

    }  
    mysqli_close($con);
    ?>

As the code is it has invalid arguments for the 2nd foreach function but I have no doubt that is not all that is wrong with it.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongpeng7744 2014-06-11 12:37
    已采纳

    It's the way you explore the array who is bad. Try like that :

    foreach ($ujson as $league)
    {
        var_dump($league['league_id']);
        // also league_name...
    
        if ( !empty($league['teams'])
        {
            foreach( $league['teams'] as $team )
            {
                var_dump($team['name_of_team']);
                // also number_of_players...
            }
        }
    }
    
    点赞 打赏 评论
  • drruhc4944 2014-06-11 10:55

    I am not sure but try this

    Write this code

    if(!empty($value))
    

    Instead of

    if (is_array($value))
    
    点赞 打赏 评论
  • duanhang032796 2014-06-11 11:05

    I have analyzed your your JSON file content. First array in your JSON content contain invalid data. That is:
    [ { league_id: "3", league_name: "League "3", teams: [] },...]

    instead of:

    [ { league_id: "3", league_name: "League 3", teams: [] },...]

    The legend name contain double quote(") in it's value. That's why, your script fails to convert JSON data into array.

    Please either remove that double quote or replace it with another character.

    点赞 打赏 评论

相关推荐