PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, December 4, 2022

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

 December 04, 2022     arrays, jsondecoder, jsonencoder, object, php     No comments   

Issue

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



Answered By - dWinder
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing