您的当前位置:首页php数组如何转换json字符串

php数组如何转换json字符串

2020-11-02 来源:乌哈旅游

php数组转换json字符串的方法:首先创建一个php示例文件;然后定义一组数组数据;最后通过“json_encode($color)”方法将数组转换成json字符串即可。

推荐:《PHP视频教程》

PHP中 数组/对象转成JSON字符串

代码如下:

<?php
 
//php语言生成json字符串
//json_encode(数组/对象);
 
//① 索引数组-->JavaScript数组
$color = array('gold','yellow','blue');
echo json_encode($color)."<br />";// ["gold","yellow","blue"]
 
//② 关联数组-->json字符串
$city = array('shandong'=>'jinan','henan'=>'zhengzhou','hebei'=>'shijiazhuang');
echo json_encode($city)."<br />";//{"shandong":"jinan","henan":"zhengzhou","hebei":"shijiazhuang"}
 
//③ 索引关联数组-->json字符串
$city2 = array('shandong'=>'jinan','henan'=>'zhengzhou','shenyang','hebei'=>'shijiazhuang');
echo json_encode($city2)."<br />";//{"shandong":"jinan","henan":"zhengzhou","0":"shenyang","hebei":"shijiazhuang"}
 
//④ 对象生成json信息-->json字符串
// (只会序列化"成员属性",不会序列化"成员方法")
class Person{
 //类内部的成员属性需要有修饰符(var/public/protected/private),其是固定语法
 public $color = "yellow";
 var $height = 170;
 function run(){
 echo "is running";
 }
}
$tom = new Person();
echo json_encode($tom); //{"color":"yellow","height":170}
显示全文