php 之 json格式

/*
JSON语法
数据在名称/值对中
数据由逗号分隔
花括号保存对象
方括号保存数组

JSON 数据的书写格式是:名称/值对
名称/值对包括字段名称(在双引号中),后面写一个冒号,然后是值;如
"myweb":"lin3615"
等价于 myweb = "lin3615"

JSON 值,可以是数字,字符串(在双引号中),逻辑值,数组{在方括号中},对象(在花括号中), null
*/

/*
mix json_decode($json [, true]) // 对$json 的格式数据解析, 为 true 时返回是数组,false 是对象
$aa = '{"a":"aa", "b": "bb"}';
print_r(json_decode($aa, true));

Array
(
    [a] => aa
    [b] => bb
)

$arr = json_decode($aa, true);
echo $arr['a']; // aa
echo $arr['b'];  // bb

$obj = json_decode($aa);
echo "<br />";
echo $obj->a; // aa
echo "<br />";
echo $obj->b; // bb
*/

// string json_encode(mix $value) 对 $value 进行 json 格式编码
/*
$arr = array('a' => 'l', 'b' => 'i', 'c' => 'n');
$str = json_encode($arr);
echo $str; // {"a":"l","b":"i","c":"n"}
*/
/*
$str = array('l', 'i', 'n');
$strs = json_encode($str);
echo $strs; // ["l","i","n"]
*/

// 对象换成了 json 格式的字符,可以保存入数据库等
class test
{
    public $a = 'lin3615';
    public $c = 'hi, world';
    private $d = 'private';

    public function  __construct()
    {
        return '__contruct';
    }
    public function ok()
    {
        return 'hi';
    }
}

$obj = new test();
$oo = json_encode($obj); // {"a":"lin3615","c":"hi, world"}
echo $oo; echo '<br />';
$str = json_encode($obj->a);
echo $str; // "lin3615"
$str2 = json_encode($obj->ok());
echo $str2; // "hi"

原文地址:https://www.cnblogs.com/lin3615/p/3661675.html