我使用以下代码从使用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;
那么我将如何处理多个结果呢?
非常感谢任何帮助。
答案 0 :(得分:39)
这是一个数组,因此您可以使用foreach
foreach ($result->GetIncomingMessagesResult->SMSIncomingMessage as $message) {
echo $message->Reference;
}
然而值得注意的是,默认情况下,只有当数组中有多个值时,PHP的SoapClient
才会将数组作为PHP数组返回 - 如果只有一个值,您将获得该值(不包含在数组中)。一个简单的方法是在SOAP_SINGLE_ELEMENT_ARRAYS
构造函数中使用选项SoapClient
;这将防止此行为并确保您始终获得数组。
答案 1 :(得分:3)
我的看法是始终确保你有一组消息,即使它是一个1的数组。这样你就不会重复任何处理。
$smsMessages = is_array( $result->GetIncomingMessagesResult->SMSIncomingMessage )
? $result->GetIncomingMessagesResult->SMSIncomingMessage
: array( $result->GetIncomingMessagesResult->SMSIncomingMessage );
foreach ( $smsMessages as $smsMessage )
{
echo $smsMessage->Reference;
}
答案 2 :(得分:2)
您需要指定SMSIncomingMessage数组对象键。
$result->GetIncomingMessagesResult->SMSIncomingMessage[0]->Reference;
或
foreach ($result->GetIncomingMessagesResult->SMSIncomingMessage as $message)
{
$reference = $message[0]->Reference;
//...
}
答案 3 :(得分:0)
迭代数组?! : - )
foreach ($result->GetIncomingMessagesResult->SMSIncomingMessage as $message)
{
$reference = $message->Reference;
//...
}
答案 4 :(得分:0)
对象转换数组
$array = (array) json_decode(['TEST'=>true]);