Sol Sol - 1 year ago 67
PHP Question

Echo CustomField from nested array object in PHP

I've read this excellent answer; How can I access an array/object?

However, I can't seem to extract the object value I need from a nested array. I'm using the campaign monitor API and it dumps out the following objects. I need to be able to echo or print_r the "Phone" custom field value:

This is what my query is producing in a var_dump($result->response);

Got subscriber

object(stdClass)#728 (6) {
string(29) ""
string(7) "Alan"
string(19) "2016-10-07 17:10:00"
string(6) "Active"
array(4) {
object(stdClass)#727 (2) {
string(5) "Phone"
string(7) "12345678"

How to echo or print_r the phone number by selecting "Key" string and grabbing the "Value" string? I've tried below (and variations) but not working;

foreach($result->response->CustomFields as $CustomField) {
if(!empty($CustomField->Key->Phone)) {
$phone = $CustomField->Key->Phone->Value;

echo 'test phone'. $phone;


The following DOES work (similar to this thread php accessing attributes in json) - however, the problem with using the integer [2] in the below is that it can potentially change to a different key, depending on number of fields in the array that a given user has populated - so this method is unreliable;


Answer Source

The moment you do this:

foreach($result->response->CustomFields as $CustomField) {

You can access the fields like this:


So if you want to process it further, you can do for example something like this:

$someClass->{$CustomField->Key} = $CustomField->Value

Which translates to: $someClass->Phone = "12345678" . It pretty much depends on what you really want to do next with the values.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download