189 8069 5689

php过滤json数据,php处理json数据

如何在PHP中解析json

目前,JSON已经成为最流行的数据交换格式之一,各大网站的API几乎都支持它。

创新互联建站始终坚持【策划先行,效果至上】的经营理念,通过多达10年累计超上千家客户的网站建设总结了一套系统有效的全网整合营销推广解决方案,现已广泛运用于各行各业的客户,其中包括:航空箱等企业,备受客户赞誉。

从5.2版本开始,PHP原生提供json_encode()和json_decode()函数,前者用于编码,后者用于解码。

一、json_encode()

该函数主要用来将数组和对象,转换为json格式。先看一个数组转换的例子:

$arr = array ('a'=1,'b'=2,'c'=3,'d'=4,'e'=5);

echo json_encode($arr);

结果为

{"a":1,"b":2,"c":3,"d":4,"e":5}

由于json只接受utf-8编码的字符,所以json_encode()的参数必须是utf-8编码,否则会得到空字符或者null。当中文使用GB2312编码,或者外文使用ISO-8859-1编码的时候,这一点要特别注意。

二、索引数组和关联数组

PHP支持两种数组,一种是只保存"值"(value)的索引数组(indexed array),另一种是保存"名值对"(name/value)的关联数组(associative array)。

由于javascript不支持关联数组,所以json_encode()只将索引数组(indexed array)转为数组格式,而将关联数组(associative array)转为对象格式。

比如,现在有一个索引数组

$arr = Array('one', 'two', 'three');

echo json_encode($arr);

结果为:

["one","two","three"]

三、类(class)的转换

下面是一个PHP的类: 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; } }

现在,对这个类的实例进行json转换:

$foo = new Foo;

$foo_json = json_encode($foo);

echo $foo_json;

输出结果是

{"public_ex":"this is public"}

可以看到,除了公开变量(public),其他东西(常量、私有变量、方法等等)都遗失了。

PHP解析JSON数据,在线等!!!

先用json_decode把json解析成一个Object。接着用php提供的foreach循环,遍历得到key-value对,就能达到你想要的东西了

怎么用php截取json里边的数据?

可以使用json_decode函数来操作json数据,下面是官方文档,你可以先看看,有问题再来问

php怎么删除json里面的数据?

参考方法就是先把文件读出来,把不要的数组元素删了后再写回去;

参考代码如下:

// std::string jsonPath // json文件路径

Json::Reader reader;

Json::Value root;

ifstream is;

is.open (jsonPath.c_str(), std::ios::binary );

if (reader.parse(is, root))

{

std::string code;

Json::Value value;

int size = root.size();

for (int i = 0; i size; i++)

{

if(条件)

{

value[i] = root[i];

}

}

is.close();

Json::FastWriter writer;

std::string json_append_file = writer.write(value);

std::ofstream ofs;

ofs.open(jsonPath.c_str());

ofs json_append_file;

ofs.close();

}


本文标题:php过滤json数据,php处理json数据
网站URL:http://cdxtjz.cn/article/dscseop.html

其他资讯