json_encode问题
这让我完全难住了:
print_r($json);
echo json_encode($json);
输出:
Array
(
[query] => dia
[suggestions] => Array
(
[0] => Diana Johnson
[1] => Diane Abbott
)
)
{"query":"dia","suggestions":[null,null]}
到底出了什么问题?
编辑 只是为了添加到这个的一般性内容中,这是另一个示例:
Array
(
[query] => david
[suggestions] => Array
(
[0] => David Cameron
[1] => David Amess
[2] => David Anderson
[3] => David Blunkett
[4] => David Burrowes
)
)
{"query":"david","suggestions":["David Cameron",null,null,null,null]}
This has got me completely stumped:
print_r($json);
echo json_encode($json);
output:
Array
(
[query] => dia
[suggestions] => Array
(
[0] => Diana Johnson
[1] => Diane Abbott
)
)
{"query":"dia","suggestions":[null,null]}
What on earth is going wrong?
edit Just to add to the general wtf-ery of this, here's another sample:
Array
(
[query] => david
[suggestions] => Array
(
[0] => David Cameron
[1] => David Amess
[2] => David Anderson
[3] => David Blunkett
[4] => David Burrowes
)
)
{"query":"david","suggestions":["David Cameron",null,null,null,null]}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将此作为答案发布,因为我需要正常答案框的完整格式化功能。
是的,它是 UTF-8 没问题。从 PHP 交互式提示中:
因此,我们可以假设您正在处理 ISO-8859 或 Windows-1252,因为我们正在处理损坏的 NBSP。 我们可以使用
iconv
:因此,这意味着您将需要不信任您的内容假设您已完成
SET NAMES
操作,将从 MySQL 中退出。显然,当您插入数据时出现了问题。您可能没有为 MySQL 提供格式良好的 UTF-8,并且它愚蠢地没有抱怨。 (如果您使用其他更智能、更正确的数据库,并尝试插入未编码的 NBSP,它们会拒绝输入。)I'm posting this as an answer because I need the full formatting abilities of the normal answer box.
Yeah, it's UTF-8 all right. From the PHP interactive prompt:
So, we can assume that you're dealing with either ISO-8859 or Windows-1252, given that we're dealing with a broken NBSP. We can fix this with
iconv
:So, this means that you are going to need to not trust what you're pulling out of MySQL, assuming you've done the
SET NAMES
thing. Clearly something has gone awry when you were inserting data. You probably weren't giving MySQL well-formed UTF-8, and it stupidly did not complain. (If you were using other, smarter, more correct databases, and tried to insert the unencoded NBSP, they would have rejected the input.)这看起来像一个自动完成脚本。我假设你的结果是从数据库加载的,你确定它们是 utf-8 吗?如果您无法通过对数组进行硬编码来复制此功能,则可能是编码问题。
根据 http://php.net/manual/en/function.json-encode .php,“此函数仅适用于 UTF-8 编码的数据。”
您还可以使用 http://php.net/manual/en/function .json-last-error.php 查看最后一个错误。
This looks like an autocomplete script. I assume your results are loaded from a database, are you sure they're utf-8? If you cannot replicate this functionality by hardcoding the array, then it's probably an encoding issue.
According to http://php.net/manual/en/function.json-encode.php, "This function only works with UTF-8 encoded data."
You can also use http://php.net/manual/en/function.json-last-error.php to see the last error.