访问数组中的显式对象

时间:2016-09-22 09:24:54

标签: php arrays json

使用api调用我正在获取存储在数组中的一系列数据对象,但是我只想打印出一些返回的对象。

所有数据都存储在$mail变量中。我希望访问交付,例如它是$mail->delivered

这是返回的样本数据 -

"""
[\n
  {\n
    "count_purchased": 0,\n
    "delivered": 1,\n
    "clicked_unique": 0,\n
    "shared": 0,\n
    "mailings": 1,\n
    "year": 2016,\n
    "month": 9,\n
    "opened": 1,\n
    "opted_out": 0,\n
    "sent": 1,\n
    "signed_up": 0,\n
  },\n
  {\n
  "count_purchased": 0,\n
  "delivered": 56,\n
  "clicked_unique": 0,\n
  "shared": 0,\n
  "mailings": 31,\n
  "year": 2016,\n
  "month": 9,\n
  "opened": 1,\n
  "opted_out": 0,\n
  "sent": 102,\n
  "signed_up": 0,\n
  }\n
]

2 个答案:

答案 0 :(得分:2)

通过一些解释来增强answer of M. I.

由于您收到JSON字符串作为回复,因此需要进行转换。方便的是,PHP具有这方面的功能,最值得注意的是json_decode

因此,如果您的回复存储在$mail中,那么我们需要做的就是将其转换为associative array或类\stdClass的对象。

你的回复会返回多个对象,所以我们需要做一些工作才能按照你想要的方式访问它:

// 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 :(得分:1)

您收到JSON作为回复。使用:

json_decode($jsonString); // to get an `JSON` object or
json_decode($jsonString, true); // to get an associative array.