简体   繁体   English

PHP foreach通过JSON和Array实现

[英]PHP foreach over JSON with Array

I have a json return that looks like this: 我有一个看起来像这样的json返回:

[output] => stdClass Object
    (
        [data] => stdClass Object
            (
                [Email] => Array
                    (
                        [0] => test1@AOL.COM
                        [1] => test2@AOL.COM
                    )

                [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? 有人有主意吗?

You are trying to access PhoneNumber and Email as properties, while they are arrays. 您尝试将PhoneNumberEmail作为属性访问,而它们是数组。

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

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

The easiest way is JSON encode your std object and then decode it back to an array: 最简单的方法是JSON编码您的std对象,然后将其解码回数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM