【问题标题】:json_encode returning null if array not accessed before如果之前未访问过数组,json_encode 返回 null
【发布时间】:2011-07-11 19:40:55
【问题描述】:

在我的代码中,我构建了一个数组并使用 json_encode 对其进行编码, json_encode 为这个数组返回 null 除非我插入指令“echo $responce->rows[0][0];”在编码之前,如果我注释掉这一行 json_encode 返回 null!

有人能找出原因吗?

echo $responce->rows[0][0];
echo json_encode($responce);

这个编码的 json 有这种行为,但适用于不同的数组:

{"rows":[{"id":"33UD","cell":["Great Yarmouth Borough Council",5875732.23,61.01]},
{"id":"41UE","cell":["Newcastle-Under-Lyme District Council",2514111.76,20.24]},
{"id":"36UF","cell":["Ryedale District Council",96439.18,1.8]},{"id":"00CM","cell":
["Sunderland City Council",16473262.71,58.48]}]}

【问题讨论】:

  • 您可以添加更多代码吗?
  • var_dump($responce) 输出什么?
  • 您是否从数据库中获取数据?
  • 我们应该猜你的代码吗?

标签: php json


【解决方案1】:

如果您的数组值未编码为utf8,您将得到json_encode 返回的null(因此它们对于json_encode 不安全)

如果您从数据库中获取数据,请尝试使用:

mysql_query('SET CHARACTER SET utf8') 在您的SELECT 声明之前

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 1970-01-01
    • 2016-05-24
    相关资源
    最近更新 更多