Search code examples
phparraysjsonnestedstdclass

How to echo nested stdClass PHP (json encode decode)


I have the following stdclass object array :

var_dump($order);

array (size=2)
'raw' => 
object(stdClass)[6]
  public 'actionCodeDescription' => string 'processing.error.203' (length=20)
  public 'params' => 
    object(stdClass)[7]
      public 'respCode_desc' => string 'Transaction rejected' (length=83)

I'm trying to retrieve and show the 'params' {'respCode_desc : "transact rejected'}

for example If I call for

actionCodeDescription I just have to echo $order->message();

    public function message()
{
    return $this->raw->actionCodeDescription;
}

what I have tried : $this->raw->params['0']->respCode_desc; It did not work I would get

Trying to get property 'respCode_desc' of non-object or
Trying to access array offset on value of type null

Any ideas what I'm I doing wrong

One more thing how do I check if respCode_desc is not empty so I can display actionCodeDescription ?

Here's my code

class Order
{
public $raw;

function __construct($obj)
{
    $this->raw = $obj;
}
    public function __toString()
{
    return json_encode($this->raw, JSON_PRETTY_PRINT);
}

Solution

  • Resolved

     <?php echo $order->getCibMessage(); ?>
    
    function getCibMessage()
    {
        $obj = $this->raw;
    
        if (isset($obj->params) && isset($obj->params->respCode_desc)) {
            return  $obj->params->respCode_desc;
        } else {
            return $obj->actionCodeDescription;
        }
    }