Logic Behind json encode and decode
Encode array to json using json_encode()
<?php
// This is a simple array
$var1 = array(
'key_name1' => 'value_name1',
'key_name2' => 'value_name2'
);
//We are converting array in encode $var1 array to json using json encode
$encode_data = json_encode($var1);
echo $encode_data;
?>
Result: Array Converted to JSON
{"key_name":"value_name","key_name1":"value_name1"}
Decode json to array using json_decode()
<?php
// This is a simple array, We are converting array in
$var1 = array(
'key_name1' => 'value_name1',
'key_name2' => 'value_name2'
);
//encode $var1 array to json using json_encode()
$encode_data = json_encode($var1);
echo $encode_data;
//decode json data($encode_data) to array, using json_decode()
$decode_data = json_decode($encode_data);
print_r($decode_data);
?>
Result: JSON Converted to Array(stdClass Object)
stdClass Object ( [key_name1] => value_name1 [key_name2] => value_name2 )
Extract data from stdClass Object
By forech
<?php
foreach ($decode_data as $value){
echo $value."<br>";
}?>
Output :
value_name1
value_name2
Fetch data from object
<?php
echo $decode_data->key_name1;
echo "<br>";
echo $decode_data->key_name2;
?>
Output :
value_name1
value_name2
Comments
Post a Comment