逐个获取stdClass对象的字段

时间:2017-09-01 09:52:19

标签: php stdclass

我收到SMS API调用的响应,如下所示

stdClass Object ( 
   [balance] => 3 
   [batch_id] => 289728321 
   [cost] => 2
   [num_messages] => 2
   [message] => stdClass Object ( 
       [num_parts] => 1
       [sender] => TXTLCL
       [content] => This is test message from abc
   ) 
   [receipt_url] => 
   [custom] => 
   [messages] => Array ( 
       [0] => stdClass Object (
              [id] => 1172603746 [recipient] => 919796736174 )
       [1] => stdClass Object ( 
              [id] => 1172603747 [recipient] => 919858566712)
   )
   [status] => success 
)

我想调整的代码如下所示

 if(count($this->capturedResponse) > 0)
 {
     foreach($this->capturedResponse as $response)
     { 
      $balance = $response[0];
      $batch_id = $response[1];
      ...
      }
 }

我无法单独分离stdClass对象字段并将它们放在相应的变量中。

请帮助!!!

3 个答案:

答案 0 :(得分:0)

您需要使用->从对象中获取元素,因此请像这样使用

 $balance = $response->balance;
 $batch_id = $response->batch_id;

相反

 $balance = $response[0];
 $batch_id = $response[1];
 ...

获取content

message
 $message = $response->message->content

通过循环尝试messages让我们知道是否有任何问题

更新

$messagesObj = $response->messages;
$messagesArr = array();
foreach($messagesObj as $key=>$value){
   $messagesArr[] = $value->recipient;
}
$messages = implode(",",$messagesArr);

您将在919796736174, 919858566712

中获得$messages

答案 1 :(得分:0)

请尝试这样

 $balance = $response->balance;
 $batch_id = $response->batch_id;

答案 2 :(得分:0)

最简单的方法是对对象进行JSON编码,然后将其解码回数组:

$capturedResponse = (object) (array(
   'balance' => 1,
   'batch_id' => 289728321,
   'cost' => 2,
   'num_messages' => 2,
   'message' => (object) (array(
       'num_parts' => 1
   ))
));

$array = json_decode(json_encode($capturedResponse), True);
echo $array['balance'];