stdClass object and foreach loops

后端 未结 5 609
日久生厌
日久生厌 2020-12-03 05:48

I am using the following code to get data from a website using Soap.

$client = new SoapClient(\'http://some.url.here\');
class SMSParam {
    public $CellNu         


        
相关标签:
5条回答
  • 2020-12-03 05:57

    Iterate over the array?! :-)

    foreach ($result->GetIncomingMessagesResult->SMSIncomingMessage as $message)
    {
        $reference = $message->Reference;
        //...
    }
    
    0 讨论(0)
  • 2020-12-03 06:00

    you need to specify your SMSIncomingMessage arrays object key.

    $result->GetIncomingMessagesResult->SMSIncomingMessage[0]->Reference;
    

    or

    foreach ($result->GetIncomingMessagesResult->SMSIncomingMessage as $message)
    {
    $reference = $message[0]->Reference;
    //...
    }
    
    0 讨论(0)
  • 2020-12-03 06:13

    It is an array, so you can loop over it easily using foreach:

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

    However it is worth noting that PHP's SoapClient by default appears to return arrays as a PHP array only when there is more than one value in the array - if there is only one value you will just get that value (not contained within an array). An easy way around this is to use the option SOAP_SINGLE_ELEMENT_ARRAYS in the SoapClient constructor; this will prevent this behaviour and ensure you always get arrays.

    0 讨论(0)
  • 2020-12-03 06:14

    My take on it is to just always make sure you have an array of messages, even if it's an array of 1. That way you don't duplicate any processing.

    $smsMessages = is_array( $result->GetIncomingMessagesResult->SMSIncomingMessage )
        ? $result->GetIncomingMessagesResult->SMSIncomingMessage
        : array( $result->GetIncomingMessagesResult->SMSIncomingMessage );
    
    foreach ( $smsMessages as $smsMessage )
    {
        echo $smsMessage->Reference;
    }
    
    0 讨论(0)
  • 2020-12-03 06:14

    Cast object to convert array

    $array = (array) json_decode(['TEST'=>true]);
    
    0 讨论(0)
提交回复
热议问题