json

xiaoxiao2021-02-28  33

toStr

<?php $a = array(); for($i = 0; $i<10;$i++){ array_push($a, $i); } $json_str = json_encode($a); print_r($json_str);

json_encode,编码为json,多好记。

但是有个坑

<?php $a = array(); for($i = 0; $i<10;$i++){ //array_push($a, $i); $a[$i.''] = $i; } $json_str = json_encode($a); print_r($json_str);哪怕换了声明,结果都是 [0,1,2,3,4,5,6,7,8,9]

所以:

1. 全数组情况下,直接打印的就是数组

2. 索引也是字符串

$a[0] == $a['0']

如果添加一个键值对的话

<?php $a = array('a'=>'a'); for($i = 0; $i<10;$i++){ //array_push($a, $i); $a[$i.''] = $i; } $json_str = json_encode($a); print_r($json_str);结果 {"a":"a","0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9}然后就是完美的json了。

toJson

$str = '[0,1,2,3,4,5,6,7,8,9]'; $a = json_decode($str); print_r($a);

json_decode解码,很好记。

结果

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 )

可以看出,所谓的json格式并不是专门的json,而是PHP中array的toString,和平时所说的json格式还是有差异的。

但是,当array中含有至少一个键值对的情况下,转化的json字符串就和平时的没有差异。

而不论什么样式,转化为的数据类型,都是array。

转载请注明原文地址: https://www.6miu.com/read-2621984.html

最新回复(0)