在PHP后端和客户端数据交互的过程中,JSON数据中有时格式不定,一会儿是数组,一会儿是对象,弄得客户端开发人员要崩溃的感觉。
因此,前后端相关人员先对PHP的json_encode函数原理有必要的了解是最重要的一个环节。
PHP中的array是个万能的数据结构,并不像其它语言根据需要的场景会定义很多约束性的数据类型来描述结构,所以PHP程序员是很难给客户端人员讲清楚返回的是什么结构的数据的。
也就变成明明是通过PHP的数组数据编码成json的,但输出值有时是数组、有时是对象的情况。
<code><span><?php </span><span>/*</span><span>如果你想生成一个json格式的数组格式(Vector)而非对象格式(Map)的,那么数据的下标:</span><span>必须是数字索引,</span><span>必须从0开始,</span><span>必须从小到大依次增加、中间不可以跳跃、顺序不可变动.</span><span>*/</span><span>//符合数组</span><span>$vector</span> = <span>[</span><span>12</span><span>,</span><span>23</span><span>,</span><span>18</span><span>];</span><span>echo</span><span>json_encode</span><span>(</span><span>$vector</span><span>);</span><span>//符合数组</span><span>$vector2</span> = <span>[</span><span>0</span> => <span>12</span><span>,</span><span>1</span> => <span>23</span><span>,</span><span>2</span> => <span>18</span><span>];</span><span>echo</span><span>json_encode</span><span>(</span><span>$vector2</span><span>);</span><span>//不符合数组,下标有跳跃</span><span>$map</span> = <span>[</span><span>0</span> => <span>12</span><span>,</span><span>1</span> => <span>23</span><span>,</span><span>2</span> => <span>18</span><span>,</span><span>4</span> => <span>20</span><span>];</span><span>echo</span><span>json_encode</span><span>(</span><span>$map</span><span>);</span><span>//不符合数组,下标顺序不对</span><span>$map</span> = <span>[</span><span>0</span> => <span>12</span><span>,</span><span>1</span> => <span>23</span><span>,</span><span>3</span> => <span>18</span><span>,</span><span>2</span> => <span>20</span><span>];</span><span>echo</span><span>json_encode</span><span>(</span><span>$map</span><span>);</span><span>//不符合数组,下标没有从0开始</span><span>$map_1</span> = <span>[</span><span>1</span> => <span>'111'</span><span>,</span><span>2</span> => <span>'asdfa'</span><span>];</span><span>echo</span><span>json_encode</span><span>(</span><span>$map_1</span><span>);</span><span>//典型的对象格式</span><span>$map_2</span> = <span>[</span><span>'abc'</span> => <span>1</span><span>,</span><span>'de'</span> => <span>2</span><span>,</span><span>'fi'</span> => <span>null</span><span>];</span><span>echo</span><span>json_encode</span><span>(</span><span>$map_2</span><span>);</span><span>/**</span><span> * 请注意上面的变量命名,对应于Hack中的概念,Vector和Map为两种数据集合类型</span><span> * 如果你需要将"索引数组"强制转化成"对象",可以这样写</span><span> * json_encode((object) $a);</span><span> * 或</span><span> * json_encode ($a, JSON_FORCE_OBJECT);</span><span> *</span><span> */</span></span></code>
解决方案是什么呢?
就是通过PHP封装Vector和Map这两种数据结构的类,在构造json输出结构时,以这两种类型做封装和转换,来确保结构的确定性。
以上就介绍了对象数组 PHP JSON数组与对象的理解,包括了对象数组方面的内容,希望对PHP教程有兴趣的朋友有所帮助。