Json Encode & Decode Any Object
<?php
//Json Encode Any Object --->Json Object
//PHP ARRAY ---->JSON_ARRAY
//Example : [10,20,30] --->[10,20,30]
// array(10,20,30) ---->[10,20,30]
//PHP ASSOCIATIVE : Key and values ---> JSON_Object
//MULTI_DEMENSIONAL Array --->Array_Objects
$student=[
//student - 1
[
'name'=>'ravi',
'class'=>12,
'passed'=>'yes',
],
//student - 2
[
'name'=>'Awnish',
'class'=>10,
'passed'=>'no',
],
];
echo "<pre>";
print_r($student);
echo "</pre>";
echo "<hr/>";
//Encode the data Json
#header("Content-Type:application/json");
$json=json_encode(["student"=>$student],JSON_PRETTY_PRINT);
echo $json;
echo "<hr/>";
echo getType($json);
echo "<hr/>";
echo $json->name; #Not Possible
#Notice: Trying to get property 'name' of non-object in
#We need to Decode : Desialiazation (JSON OBJECT-->PHP OBJECT)
$student_obj=json_decode($json);
echo "<hr/>";
echo getType($student_obj);
echo "<hr/>";
$student = $student_obj->student;
echo getType($student);
echo "<hr/>";
$object=$student[0];
echo "<hr/>";
$name = $object->name;
$class = $object->class;
$status = $object->passed;
echo "<hr/>";
echo "Student name :{$name} <br/>";
echo "Student class :{$class} <br/>";
echo "Student status :{$status} <br/>";
0 Comments