PHP笔记--json_decode与json_encode

json_decode($data,[bool]):将json数据转换为对象或数组
参数说明:
$data:要转换的json字符串
$bool:可选(true/false)默认true,当为false时转换为php数组、

不指定第二个参数或设置为false返回对象

$json = '{
	"name":"程序猿",
	"age":20,
	"hobby":[1,2],
	"attribute":{
		"type":"男"
	}
}';
var_dump(json_decode($json));
//返回结果
object(stdClass)[1]
  public 'name' => string '程序猿' (length=9)
  public 'age' => int 20
  public 'hobby' => 
    array (size=2)
      0 => int 1
      1 => int 2
  public 'attribute' => 
    object(stdClass)[2]
      public 'type' => string '男' (length=3)

将第二个参数设置为true返回数组

$json = '{
	"name":"程序猿",
	"age":20,
	"hobby":[1,2],
	"attribute":{
		"type":"男"
	}
}';
var_dump(json_decode($json,true));
//返回结果
:\wamp64\www\fx\test.php:18:
array (size=4)
  'name' => string '程序猿' (length=9)
  'age' => int 20
  'hobby' => 
    array (size=2)
      0 => int 1
      1 => int 2
  'attribute' => 
    array (size=1)
      'type' => string '男' (length=3)

json_encode($arr):将数组或对象转换为json字符串
如:

class Foo{
	public $foo_name = "chs";
}

$json=new Foo();
var_dump(json_encode($json));
//打印结果
D:\wamp64\www\fx\test.php:15:string '{"foo_name":"chs"}' (length=18)

数组

$json=['name'=>'tes'];
var_dump(json_encode($json));
D:\wamp64\www\fx\test.php:15:string '{"name":"tes"}' (length=14)
发布了44 篇原创文章 · 获赞 1 · 访问量 1559

猜你喜欢

转载自blog.csdn.net/weixin_45143481/article/details/104188730