SamXronn SamXronn - 2 months ago 5
JSON Question

Accessing explicit objects within an array

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 -

"""
[\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
]

Answer

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);
}
Comments