-1

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); 
Community
  • 1
  • 1
SolaceBeforeDawn
  • 958
  • 1
  • 8
  • 16

1 Answers1

1

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.

walther
  • 13,466
  • 5
  • 41
  • 67
  • This looks helpful, however I wasn't able to get it working. In this example, how would I specify the key to be "phone". I tried this: if ($CustomField->Key == 'Phone') { echo 'test phone'. $CustomField->Value; } – SolaceBeforeDawn Nov 14 '16 at 12:04
  • @Sol, key of what? How do you intend to use it?? You already know the key, it's: `$CustomField->Key`. – walther Nov 14 '16 at 12:06
  • Sorry, I'm not getting that. I simply want to target the "Key" > "Phone" and extract the phone number. Can you provide a clearer example ? – SolaceBeforeDawn Nov 14 '16 at 12:12
  • @Sol, what isn't working with this code `if ($CustomField->Key == 'Phone') { echo 'test phone'. $CustomField->Value; }` ? – walther Nov 14 '16 at 12:23
  • Well now, that's the same code I was using - and now it is working.... very strange!! Super moon madness. Thanks for your help walther ;) – SolaceBeforeDawn Nov 14 '16 at 12:31