PHP Json
- 2020年6月08日
- 技術情報
Today I will talk about how to operate Json data in PHP especially using json_encode
& json_decode
.
So, Lets get started. We have an array like this.
<?php
$months = array("Jan"=>"01","Feb"=>"02","March"=>"03","April"=>"04");
?>
If we want to change that array to json format, we can do like this.
<?php
$months = array("Jan"=>"01","Feb"=>"02","March"=>"03","April"=>"04");
echo json_encode($months);
?>
So What about decoding, decoding the also similar with encoding.
<?php
$json = '{"Jan":"01","Feb":"02","March":"03","April":"04"}';
//we can treat the decoded data in two ways (object & array)
//treating like an object.
$obj = json_decode($json);
echo $obj->Jan;
// treating like an array
$array = json_decode($json,true);
echo $array['Jan'];
?>
The sample concept if you want to loop through the decoded json.
<?php
$json = '{"Jan":"01","Feb":"02","March":"03","April":"04"}';
$array = json_decode($jsonobj, true);
foreach($array as $key => $value) {
echo $key . " => " . $value . "<br>";
}
<?php
$json = '{"Jan":"01","Feb":"02","March":"03","April":"04"}';
$obj = json_decode($jsonobj);
foreach($obj as $key => $value) {
echo $key . " => " . $value . "<br>";
}
By Yuuma
yuuma at 2020年06月08日 11:00:54