【问题标题】:Json Convert to Std Object and Access Different data types of a Std Object (i.e Array or Attribute)?Json 转换为标准对象并访问标准对象的不同数据类型(即数组或属性)?
【发布时间】:2017-01-18 04:03:37
【问题描述】:

我有一个 json 字符串类型转换为 std 对象。由 AWS SNS 返回,一些被转换为数组,一些被转换为标准对象属性。我正在尝试从中解码属性“[bouncedRecipients]”,它有时是一个数组,有时它是一个 std 对象属性。

无法使用它,因为我尝试了以下代码,该代码仅在它是 JSON 对象属性但不能作为数组工作时才有效。

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

这里是返回数据类型的示例。其他变体类型 [bouncedRecipients] 成为标准对象属性。

[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
                )

        )

)

【问题讨论】:

    标签: php json amazon-sns


    【解决方案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 或类似循环。

    【讨论】:

    • 我稍微更新了我的答案,以解决它可能是数组或对象的可能性。让我知道这是否有意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 2017-03-12
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    相关资源
    最近更新 更多