在这里记录一下有关ajax的json代码
1 <?php 2 //在php里边生成json信息(json_encode()提供 json_decode()接收) 3 //json_encode(数组、对象); 4 5 //索引数组 6 $color=array('red','blue','green'); 7 echo json_encode($color),"<br />"; //字符串 ["red","blue","green"] 8 9 //关联数组 10 $city=array('hebei'=>'shijiazhuang','shandong'=>'jinan','henan'=>'zhengzhou'); 11 echo json_encode($city),"<br />"; //{"hebei":"shijiazhuang","shandong":"jinan","henan":"zhengzhou"} 12 13 //索引关联数组 14 $city1=array('hebei'=>'shijiazhuang','shandong'=>'jinan','henan'=>'zhengzhou','shanghai'); 15 echo json_encode($city1),"<br />"; //{"hebei":"shijiazhuang","shandong":"jinan","henan":"zhengzhou","0":"shanghai"} 16 17 //多维数组,看当前维数的类型; 18 //关联/索引关联维数------>json对象 19 //索引----------------->json数组 20 21 //对象生成json信息 22 class Person{ 23 public $name="tom"; 24 public $age=23; 25 public function run(){ 26 echo "is running"; 27 } 28 } 29 $per=new Person(); 30 //生成json信息只考虑“属性” 31 echo json_encode($per); //{"name":"tom","age":23}
json反编码
1 <?php 2 3 //解析、反编码json信息 4 5 $city=array('hebei'=>'shijiazhuang','shandong'=>'jinan','henan'=>'zhengzhou'); 6 $jn_city=json_encode($city); 7 8 //反编码 9 //true和false的区别: 10 //true--->array(数组) false--->object(对象) 11 12 $fan_city=json_decode($jn_city,false); 13 var_dump($fan_city);
//object(stdClass)#1 (3) { ["hebei"]=> string(12) "shijiazhuang" ["shandong"]=> string(5) "jinan" ["henan"]=> string(9) "zhengzhou" } 14 15 $fan_city=json_decode($jn_city,true); 16 var_dump($fan_city); //array(3) { ["hebei"]=> string(12) "shijiazhuang" ["shandong"]=> string(5) "jinan" ["henan"]=> string(9) "zhengzhou" } 17 18 //给一个自定义的“json字符串”反编码操作 19 //反编码的json字符串对定义的“单双引号”有要求 20 $jn_str="{name:'tom',color:'red',age:'5'}"; //null 21 $jn_str="{'name':'tom','color':'red','age':'5'}"; //null 22 23 $jn_str='{"name":"tom","color":"red","age":"5"}'; //string(38) "{"name":"tom","color":"red","age":"5"}" 24 25 $fan_str=json_decode($jn_str,true); 26 var_dump($jn_str);
自定义字符串反编码操作,对单双引号有要求(php版本问题)