Json Encode / Decode   PHP


Summary

usage of json_encode / json_decode


<?php 
$data = [];
$data['animal'] = [];
$data['animal']['dog'] = ['name' => 'abc', 'age' => 5];
$data['animal']['cat'] = ['name' => 'efg', 'age' => 7];
$data['page'] = ['current' => 1, 'total' => 10];

echo '<pre>';

$json = json_encode($data);

print_r($json);
echo PHP_EOL;

$obj = json_decode($json);
print_r($obj);
echo $obj->page->current . PHP_EOL;

$arr = json_decode($json, true);
print_r($arr);
echo $arr['page']['current'] . PHP_EOL;

$data2 = (object) []; // same as 'new stdClass()'
$data2->result = new stdClass();
$data2->result->code = 1;
$data2->result->msg = 'text';

print_r($data2);
print_r(json_encode($data2));

echo '</pre>';


Result

{"animal":{"dog":{"name":"abc","age":5},"cat":{"name":"efg","age":7}},"page":{"current":1,"total":10}}
stdClass Object
(
    [animal] => stdClass Object
        (
            [dog] => stdClass Object
                (
                    [name] => abc
                    [age] => 5
                )

            [cat] => stdClass Object
                (
                    [name] => efg
                    [age] => 7
                )

        )

    [page] => stdClass Object
        (
            [current] => 1
            [total] => 10
        )

)
1
Array
(
    [animal] => Array
        (
            [dog] => Array
                (
                    [name] => abc
                    [age] => 5
                )

            [cat] => Array
                (
                    [name] => efg
                    [age] => 7
                )

        )

    [page] => Array
        (
            [current] => 1
            [total] => 10
        )

)
1
stdClass Object
(
    [result] => stdClass Object
        (
            [code] => 1
            [msg] => text
        )

)
{"result":{"code":1,"msg":"text"}}

References


Tags

#json 


[ Edit (Author only) ]