<?php
//1.将一维数组转换成json格式
$arr1 = array(); $arr1["name"] = "zhangsan";
$arr1["age"] = 25; $arr1["address"] = "安徽";
echo json_encode($arr1);
//{ "name":"zhangsan","age":25,"address":"\u5b89\u5fbd"} echo "<hr/>";
//2.将多维数组转换成json格式
$arr2 = array();
$arr2["users"]["beijing"]["username"] = "gem";
$arr2["users"]["beijing"]["age"] = 22;
$arr2["users"]["anhui"]["username"] = "wolf";
$arr2["users"]["anhui"]["age"] = 23; echo json_encode($arr2);
//{ "users":{ "beijing":{ "username":"gem","age":22},"anhui":{ "username":"wolf","age":23}}}
echo "<hr/>";
//3.将对象转换为json格式
class Person{
public $name;
public function setName($name){
$this->name = $name;
}
}
$p = new Person();
$p->setName("lisi");
echo json_encode($p);
//{ "name":"lisi"}类的属性为私有变量时不会输出
echo "<hr/>";
//4.将json格式转换为数组格式
$json = '{"users":{"beijing":{"username":"gem","age":22},"anhui":{"username":"wolf","age":23}}}';
var_dump(json_decode($json,true));