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,
}
]
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);
}
You are getting an JSON
as response. Use:
json_decode($jsonString); // to get an `JSON` object or
json_decode($jsonString, true); // to get an associative array.