php - json 大括号保存对象,为什么关联数组在json中表现为对象,用{}包裹关联数组的数据?
黄舟
黄舟 2017-04-11 10:17:58
[PHP讨论组]

实验数据:

//关联数组
$result_array1['msg'] = 13;
$result_array1['infor'] = 24;
//索引数组
$arr = array(0,1,3);
$arr[0] = $result_array1;
$arr[1] = $result_array1;
$arr[2] = $result_array1;
$arr[3] = 123;
$arr[4] = 3243;

$result_array['msg'] = 13;
$result_array['infor'] = 24;
$result_array['ra1'] = $arr;

var_dump($result_array);
var_dump(json_encode($result_array));

浏览器输出:

array (size=3)
  'msg' => int 13
  'infor' => int 24
  'ra1' => 
    array (size=5)
      0 => 
        array (size=2)
          'msg' => int 13
          'infor' => int 24
      1 => 
        array (size=2)
          'msg' => int 13
          'infor' => int 24
      2 => 
        array (size=2)
          'msg' => int 13
          'infor' => int 24
      3 => int 123
      4 => int 3243

string '{"msg":13,"infor":24,"ra1":[{"msg":13,"infor":24},{"msg":13,"infor":24},{"msg":13,"infor":24},123,3243]}' (length=104)

实验结论:关联数组json表现为{},索引数组表现为:[]
这个不是和json定义违背了吗?:

数组(在中括号中)

对象(在大括号中)

难道关联数组在PHP中是对象,而索引数组就不是对象,那它们的区别是什么????

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(2)
大家讲道理
    A string is a sequence of zero or more Unicode characters [UNICODE].
   Note that this citation references the latest version of Unicode
   rather than a specific release.  It is not expected that future
   changes in the UNICODE specification will impact the syntax of JSON.

   An object is an unordered collection of zero or more name/value
   pairs, where a name is a string and a value is a string, number,
   boolean, null, object, or array.

   An array is an ordered sequence of zero or more values.

http://www.faqs.org/rfcs/rfc7...

对象:无序的一系列值
数组:有序的一系列值

这是json的标准说明,所以没毛病

伊谢尔伦

没毛病啊
'{"msg":13,"infor":24,"ra1":[{"msg":13,"infor":24},{"msg":13,"infor":24},{"msg":13,"infor":24},123,3243]}'
ral的值是数组,所以用[]包含。
然后值的前三个又是一个json对象

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号