Home  >  Article  >  php教程  >  php之json_encode和json_decode

php之json_encode和json_decode

WBOY
WBOYOriginal
2016-06-06 16:05:09974browse

1.当array是一个从0开始的连续数组时,json_encode出来的结果是一个由[]括起来的字符串

而当array是不从0开始或者不连续的数组时,json_encode出来的结果是一个由{}括起来的key-value模式的字符串

$test = array();
$test[] = 1;
$test[] = 1;
$test[] = 1;
DEBUG(json_encode($test));
结果:
[1,1,1]

$test = array(); 
$test[] = 1; 
$test[] = 1; 
$test[] = 1; 
unset($test[0]); 
DEBUG(json_encode($test));
结果:
{"1":1,"2":1}

2.当字符串为[1,1,1] 这种模式时,json_decode默认解析出来的结果是一个数组,

当字符串为{"1":1,"2":1} 这种模式时,json_decode默认解析出来的结果是一个对象,此时可以设置它的第二个参数为true强制让它返回数组

 

3.由于php无法区分一维数组和二维数组,才会出现以上情况,因为使用json编码时推荐将第二个参数设置为true

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn