Json转换为Std对象并访问Std对象的不同数据类型(即数组或属性)?

时间:2016-09-09 23:49:04

标签: php json amazon-sns

我有一种转换为std对象的json字符串。由AWS SNS返回,一些转换为数组,一些转换为Std对象属性。我试图从这些解码属性“[bouncedRecipients]”,它有时是一个数组,有时它是一个std对象属性。

无法随身携带,因为我尝试的是代码,只有在它的JSON对象属性但不作为数组工作时才有效。

$mail=json_decode($data->bounce->bouncedRecipients);

以下是返回数据类型的示例。其他变量类型[bouncedRecipients]成为std对象属性。

[2016-09-10 04:15:10] SNS邮件

stdClass Object
(
    [notificationType] => Bounce
    [bounce] => stdClass Object
        (
            [bounceType] => Permanent
            [bounceSubType] => Suppressed
            [bouncedRecipients] => Array
                (
                    [0] => stdClass Object
                        (
                            [emailAddress] => exmaple@gmail.com
                            [action] => failed
                            [status] => 5.1.1
                            [diagnosticCode] => Amazon SES has suppressed sending to this address because it has a recent history of bouncing as an invalid address. For more information about how to remove an address from the suppression list, see the Amazon SES Developer Guide: http://docs.aws.amazon.com/ses/latest/DeveloperGuide/remove-from-suppressionlist.html 
                        )

                )

            [timestamp] => 2016-09-09T22:45:24.978Z
            [feedbackId] => 01000157112sasasec-76df-11e6-9e95-5db9bsasas-000000
            [reportingMTA] => dns; amazonses.com
        )

    [mail] => stdClass Object
        (
            [timestamp] => 2016-09-09T22:45:05.000Z
            [source] => info@example.com
            [sourceArn] => arn:aws:ses:ssss.com
            [sendingAccountId] => 973549asasas9
            [messageId] => 0100015711207assaasa-4c54-afb2-34f9868a4e1c-000000
            [destination] => Array
                (
                    [0] => example@gmail.com
                )

        )

)

1 个答案:

答案 0 :(得分:1)

假设您已经解码了JSON数据,那么你可以做这样的事情:

foreach ($data->bounce->bouncedRecipients as $bouncedRecipient) {
    // $bouncedRecipient is an object so use it as such, ie.
    echo $bouncedRecipient->emailAddress;
}

如果您需要检查类型,您还可以执行以下操作:

if (is_object($data->bounce->bouncedRecipients)) {
    $data->bounce->bouncedRecipients = [$data->bounce->bouncedRecipients];
} elseif (!is_array($data->bounce->bouncedRecipients)) {
    die("What is this data you have given me?");
}

然后继续前面的foreach或类似的循环。