dsjws44266 2016-09-22 09:24
浏览 23
已采纳

访问数组中的显式对象

Using an api call I'm fetching a range of data objects stored within an array however I only want to print out some of the objects returned.

All of the data is stored within the $mail variable. I'm looking to access delivered for example would it be something like $mail->delivered

This is the sample data returned -

"""
[

  {

    "count_purchased": 0,

    "delivered": 1,

    "clicked_unique": 0,

    "shared": 0,

    "mailings": 1,

    "year": 2016,

    "month": 9,

    "opened": 1,

    "opted_out": 0,

    "sent": 1,

    "signed_up": 0,

  },

  {

  "count_purchased": 0,

  "delivered": 56,

  "clicked_unique": 0,

  "shared": 0,

  "mailings": 31,

  "year": 2016,

  "month": 9,

  "opened": 1,

  "opted_out": 0,

  "sent": 102,

  "signed_up": 0,

  }

]
  • 写回答

2条回答 默认 最新

  • duanna3634 2016-09-22 10:26
    关注

    Enhancing the answer of M. I. with a little bit of explanation:

    Since you are getting a JSON string as a response, you need to convert it. Conveniently, PHP has a function for that, most notably json_decode.

    So if your response is stored into $mail, then all we need to do is convert it into an associative array or an object of the class \stdClass.

    Your response returns multiple objects so we need to do some work before we can access it the way, you want it to:

    // Given the content of mail is your given json string
    
    // The second parameter allows us to use each entry of $mailData as \stdClass.
    // If you want to use an assiocative array instead, you can put in true for the second parameter.
    $mailData = json_decode($mail, false); // false can also be omitted in this case.
    echo $mailData[0]->sent; // 1
    echo $mailData[1]->sent; // 102
    
    // Now you are able to do fancy stuff with the data, for example loop over it.
    foreach($mailData as $singleMailData) {
        // Do whatever you want with each entry. In my example I just print out the data.
        var_dump($singleMailData);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据