json解析:
json_encode
json_decode
将array转成json字符串:
$res = [
'search' => $request -> post('json'),
'code' => 200,
];
return json_encode($result);
反之,使用json_decode
:
$json_string='{"id":1,"name":"jb51"} ';
$obj=json_decode($json_string);
echo $obj->id;
echo $obj->name;
还可以对已有的class进行json转换,将公开变量转为json:
class Foo {
const ERROR_CODE = '404';
public $public_ex = 'this is public';
private $private_ex = 'this is private!';
protected $protected_ex = 'this should be protected';
public function getErrorCode() {
return self::ERROR_CODE;
}
}
//操作
$foo = new Foo;
$foo_json = json_encode($foo);
echo $foo_json; // {"public_ex":"this is public"}
详细请参看:在PHP语言中使用JSON - 阮一峰的网络日志