Home >Backend Development >PHP Tutorial >In-depth understanding of PHP JSON arrays and objects_php examples
During the interaction between the PHP backend and the client data, the JSON data is sometimes in an uncertain format. Sometimes it is an array, sometimes it is an object, which makes the client developer feel like it is about to collapse.
Therefore, it is the most important step for front-end and back-end related personnel to have a necessary understanding of the principle of PHP's json_encode function.
The array in PHP is a universal data structure. Unlike other languages that define many restrictive data types to describe the structure according to the required scenarios, it is difficult for PHP programmers to clearly explain to the client what structure is returned. of data.
It becomes a situation where the array data is obviously encoded into json through PHP, but the output value is sometimes an array and sometimes an object.
<?php /* 如果你想生成一个json格式的数组格式(Vector)而非对象格式(Map)的,那么数据的下标: 必须是数字索引, 必须从0开始, 必须从小到大依次增加、中间不可以跳跃、顺序不可变动. */ //符合数组 $vector = [ 12, 23, 18 ]; echo json_encode($vector); //符合数组 $vector2 = [ 0 => 12, 1 => 23, 2 => 18 ]; echo json_encode($vector2); //不符合数组,下标有跳跃 $map = [ 0 => 12, 1 => 23, 2 => 18, 4 => 20 ]; echo json_encode($map); //不符合数组,下标顺序不对 $map = [ 0 => 12, 1 => 23, 3 => 18, 2 => 20 ]; echo json_encode($map); //不符合数组,下标没有从0开始 $map_1 = [ 1 => '111', 2 => 'asdfa' ]; echo json_encode($map_1); //典型的对象格式 $map_2 = ['abc' => 1, 'de' => 2, 'fi' => null]; echo json_encode($map_2); /** * 请注意上面的变量命名,对应于Hack中的概念,Vector和Map为两种数据集合类型 * 如果你需要将"索引数组"强制转化成"对象",可以这样写 * json_encode((object) $a); * 或 * json_encode ($a, JSON_FORCE_OBJECT); * */
What is the solution?
It is a class that encapsulates the two data structures of Vector and Map through PHP. When constructing the json output structure, these two types are used for encapsulation and conversion to ensure the certainty of the structure.
The above is the PHP JSON array and object introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the Script House website!