stdClass 对象和 foreach 循环

2022-08-31 00:11:55

我使用以下代码从使用Soap的网站获取数据。

$client = new SoapClient('http://some.url.here');
class SMSParam {
    public $CellNumber;
    public $AccountKey;
    public $MessageCount;
    public $MessageBody;
    public $Reference;

}
$parameters = new SMSParam;
$parameters -> AccountKey = "$sms_key";
$parameters -> MessageCount = "25";
$Result = $client->GetIncomingMessages($parameters);
echo "<pre>";
print_r($Result);
echo "</pre>";

下面是输出的示例:

stdClass Object
(
    [GetIncomingMessagesResult] => stdClass Object
        (
            [SMSIncomingMessage] => Array
                (
                    [0] => stdClass Object
                        (
                            [OutgoingMessageID] => data
                            [Reference] => data
                            [MessageNumber] => data
                            [PhoneNumber] => data
                            [Message] => data
                            [ReceivedDate] => data
                        )

                    [1] => stdClass Object
                        (
                            [OutgoingMessageID] => data
                            [Reference] => data
                            [MessageNumber] => data
                            [PhoneNumber] => data
                            [Message] => data
                            [ReceivedDate] => data
                        )

                    [2] => stdClass Object
                        (
                            [OutgoingMessageID] => data
                            [Reference] => data
                            [MessageNumber] => data
                            [PhoneNumber] => data
                            [Message] => data
                            [ReceivedDate] => data
                        )

                )

        )

)

如果只返回1个结果,我可以简单地做这样的事情:

$reference = $result->GetIncomingMessagesResult->SMSIncomingMessage->Reference;

那么,我该如何处理多个结果呢?

任何帮助将不胜感激。


答案 1

它是一个数组,因此您可以使用以下命令轻松循环访问它:foreach

foreach ($result->GetIncomingMessagesResult->SMSIncomingMessage as $message) {
    echo $message->Reference;
}

但是值得注意的是,默认情况下,PHP似乎仅在数组中有多个值时才将数组作为PHP数组返回 - 如果只有一个值,您将只获得该值(不包含在数组中)。解决此问题的一种简单方法是使用构造函数中的选项;这将防止此行为,并确保您始终获得数组。SoapClientSOAP_SINGLE_ELEMENT_ARRAYSSoapClient


答案 2

我的看法是始终确保你有一个消息数组,即使它是一个1的数组。这样,您就不会复制任何处理。

$smsMessages = is_array( $result->GetIncomingMessagesResult->SMSIncomingMessage )
    ? $result->GetIncomingMessagesResult->SMSIncomingMessage
    : array( $result->GetIncomingMessagesResult->SMSIncomingMessage );

foreach ( $smsMessages as $smsMessage )
{
    echo $smsMessage->Reference;
}

推荐