我正在使用以下代码使用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;
那么我将如何处理多个结果?
任何帮助将不胜感激。
这是一个数组,因此您可以使用foreach
轻松地对其进行循环:
foreach ($result->GetIncomingMessagesResult->SMSIncomingMessage as $message) {
echo $message->Reference;
}
但是值得注意的是,默认情况下,PHP的SoapClient
似乎仅在数组中包含多个值时才将数组作为PHP数组返回-如果只有一个值,您只会得到该值(不包含在其中数组)。解决此问题的一种简单方法是在SOAP_SINGLE_ELEMENT_ARRAYS
构造函数中使用选项SoapClient
。这将防止此行为,并确保始终获得数组。
我的看法是,始终确保您有一组消息,即使它是1的数组,也不会重复任何处理。
$smsMessages = is_array( $result->GetIncomingMessagesResult->SMSIncomingMessage )
? $result->GetIncomingMessagesResult->SMSIncomingMessage
: array( $result->GetIncomingMessagesResult->SMSIncomingMessage );
foreach ( $smsMessages as $smsMessage )
{
echo $smsMessage->Reference;
}
您需要指定您的SMSIncomingMessage数组对象键。
$result->GetIncomingMessagesResult->SMSIncomingMessage[0]->Reference;
或
foreach ($result->GetIncomingMessagesResult->SMSIncomingMessage as $message)
{
$reference = $message[0]->Reference;
//...
}
迭代数组?! :-)
foreach ($result->GetIncomingMessagesResult->SMSIncomingMessage as $message)
{
$reference = $message->Reference;
//...
}
转换对象转换数组
$array = (array) json_decode(['TEST'=>true]);