Sol Sol - 22 days ago 8
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) {
["EmailAddress"]=>
string(29) "example@mail.com"
["Name"]=>
string(7) "Alan"
["Date"]=>
string(19) "2016-10-07 17:10:00"
["State"]=>
string(6) "Active"
["CustomFields"]=>
array(4) {
[0]=>
object(stdClass)#727 (2) {
["Key"]=>
string(5) "Phone"
["Value"]=>
string(7) "12345678"
}
[snip]


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;

print_r($result->response->CustomFields[2]->Value);

Answer

The moment you do this:

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

You can access the fields like this:

$CustomField->Key
$CustomField->Value

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.