PHP使用Array预测JSON

时间:2022-10-26 11:05:18

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?

但这是空的。有人有想法吗?

2 个解决方案

#1


1  

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

您尝试访问PhoneNumber和Email作为属性,而它们是数组。

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

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

#2


1  

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;
}

#1


1  

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

您尝试访问PhoneNumber和Email作为属性,而它们是数组。

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

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

#2


1  

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;
}