Search code examples
phparraysobjectjsondecoderjsonencoder

How to maintain object state after JSON Encode/Decode in PHP


The below method have changed property instance in object into array but the requirement have different, the result of response will be same required after manipulation.

<?php

$data =  array('statusCode'=>200,
               'statusDescripion'=>'success',
               'data'=> array('companyImage'=>new StdClass(),
               'profile'=>array())
              );

echo "<br><br> Encoded data coming from API<br>";
echo $encodeData = json_encode($data,true);

//echo "<br><br> Decode data for Manipulation <br>";
$decodeData = json_decode($encodeData,true);
//print_r($decodeData);
if($decodeData['statusCode'] == 200){
    $data_ = array('statusCode'=>$decodeData['statusCode'],
                   'statusDescripion'=>$decodeData['statusDescripion'],
                   'data'=>$decodeData['data'],
                   'url'=>"php.com");
}

echo "<br><br> After Manipulation <br>";
echo json_encode($data_,true);

enter image description here


Solution

  • From json-decode documentation:

    When TRUE, returned objects will be converted into associative arrays

    You using it so the object are convert into array - if you want it to be object (aka {}) just remove the true from the line:

    $decodeData = json_decode($encodeData,true);
    

    To:

    $decodeData = json_decode($encodeData);
    

    And by the way, json-encode doesn't get true as second argument, I think you wanted JSON_FORCE_OBJECT