douhuang2218 2017-08-21 00:02
浏览 125
已采纳

通过PHP访问JSON中的数据

I am trying to access data that is generated via directory services from a database creating ics files that are being sent to a website via JSON encoding.

There are multiple files or unknown amount being generated. My main issue at this point, is I need to parse the information out of the JSON files back into ics files.

What I am stuck with at the moment is reading the information IN the JSON files.

The JSON files are something like this:

{
  "SMSDATA": {
      "date": 20170817062448,
      "person": {
          "data":[{
             "person": 321654978,
             "information": "person information"
          },{
             "person": 3216549,
             "information": "person information"
          }]
}}

What I am trying to do is dig deep and get the person and information data out into the ics file.

What I have at the moment in PHP to simply display the data to see if I am accessing the correct data is:

    $str = '../filename/test.json'; // The location of the files
    $contents = file_get_contents($str);  // get the information from the file
    $decode = json_decode($contents, true); // Creates the JSON as an array

    //array loop
    foreach($decode as $key => $value){
    echo $value["person"]. " -> " . $value["information"]. "<br>"; // Should display the information needed
    print_r ($value);  // test dump of data
}

I'm well aware that I'm not digging deep enough. I found this resourse really helpful: How do I extract data from JSON with PHP?, as well as Convert and Loop through JSON with PHP and JavaScript Arrays/Objects. I also believe that ICal Parser will be of great use but not sure how to use it at this stage.

I want to just make sure I'm reading the correct data for now, then next step will be to create the .ics files with the person and information data.

Thank you everyone for your help.

(BTW, I've only been using PHP for a couple months)

  • 写回答

2条回答 默认 最新

  • dqm4675 2017-08-21 00:11
    关注

    You are correct, you are not starting your loop on the correct array member.

    $contents = '{
            "SMSDATA": {
                "date": 20170817062448,
                "person": {
                    "data":[{
                       "person": 321654978,
                       "information": "person information"
                    },{
                       "person": 3216549,
                       "information": "person information"
                    }]
                }
        }
    }';
    
    $decode = json_decode($contents, true);
    print_r($decode);
    
    foreach($decode['SMSDATA']['person']['data'] as $value){
        echo $value["person"]. " -> " . $value["information"]. "<br>";
    }
    

    Results

    321654978 -> person information<br>
    3216549 -> person information<br>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?