Kevin.a
Kevin.a

Reputation: 4296

How to get nested value in response object

I have the following code :

if($response['response']){
    $code = json_decode($response['response']);

    foreach($code as $err){
        echo '<pre/>';
        print_r($err);
    }
}

Without decoding it, it just returns some JSON. But when i decode it returns an array that I cannot access. Here is the response :

BAD_REQUEST
Array
(
    [0] => stdClass Object
        (
            [code] => INVALID_POSTCODE
            [message] => The provided postcode value dsdasdsa is not valid postcode in The Netherlands.
        )

    [1] => stdClass Object
        (
            [code] => NOT_VALID_URL
            [message] => The field ORWebsite value is not valid url.
        )

)

I wanna access the code value. I tried :

print_r($err[0]); this returned the first letter of "BAD REQUEST", so just a B. It sees the returned response as a string for some reason. How do i access 'code'

stdClass::__set_state(array(
   'status' => 'BAD_REQUEST',
   'errors' => 
  array (
    0 => 
    stdClass::__set_state(array(
       'code' => 'INVALID_POSTCODE',
       'message' => 'The provided postcode value dsdasdsa is not valid postcode in The Netherlands.',
    )),
    1 => 
    stdClass::__set_state(array(
       'code' => 'NOT_VALID_URL',
       'message' => 'The field ORWebsite value is not valid url.',
    )),
  ),
))

Upvotes: 1

Views: 100

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

change code like below:

if($response['response']){
   //use true as second parameter to convert it to normal php array
    $code = json_decode($response['response'],true); 

    //Above array have errors index array so iterate over it
    foreach($code['errors'] as $err){ 
        echo $err['code']; //print the error code
    }
}

Upvotes: 1

Related Questions