Get fields of stdClass object one by one

846 Views Asked by At

I am getting response from SMS API call like below

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 
)

The code which I am trying to tweak is like below

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

I am not able to separate the stdClass Object fields separately and put them in their corresponding variables.

Please Help !!!

3

There are 3 best solutions below

0
On

The easiest way is to JSON-encode your object and then decode it back to an array:

$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'];
13
On

You need to use -> to get element from object, so use like this

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

Instead

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

To get content of message

 $message = $response->message->content

Try yourself for messages by loop let us know if any problem

Update

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

You will get 919796736174, 919858566712 in $messages

0
On

Please try like this

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