Tom Canfarotta
Tom Canfarotta

Reputation: 773

PHP foreach over JSON with Array

I have a json return that looks like this:

[output] => stdClass Object
    (
        [data] => stdClass Object
            (
                [Email] => Array
                    (
                        [0] => [email protected]
                        [1] => [email protected]
                    )

                [PhoneNumber] => Array
                    (
                        [0] => 2031234569
                    )

            )

What i need to do is be able to loop through the phones and emails and get them all.

I have tried:

foreach ($json_result->output->data as $data) {
$phone = $data->PhoneNumber;
$email = $data->Email;
}

but this is returning empty. Anyone have an idea?

Upvotes: 0

Views: 32

Answers (2)

Meathanjay
Meathanjay

Reputation: 2073

The easiest way is JSON encode your std object and then decode it back to an array:

$array = json_decode(json_encode($object), true);
foreach($array as $data) {
   $phone = $data->PhoneNumber;
   $email = $data->Email;
}

Upvotes: 1

yk11
yk11

Reputation: 768

You are trying to access PhoneNumber and Email as properties, while they are arrays.

foreach ($json_result->output->data->Email as $email_address) {
    echo $email_address;
}

foreach ($json_result->output->data->PhoneNumber as $phone_number) {
    echo $phone_number;
}

Upvotes: 1

Related Questions