gpt4 book ai didi

php json_encode 部分不适用于数组

转载 作者:行者123 更新时间:2023-12-02 23:06:37 25 4
gpt4 key购买 nike

我有一个 PHP 代码,需要将数据库表数据编码为 json。所以我使用了 json_encode()。

我使用此处给出的表格 - http://www.geekality.net/2011/08/21/country-names-continent-names-and-iso-3166-codes-for-mysql/

对于不同的输入,此代码的行为似乎有所不同。

查询 - $query = "SELECT * FROM states "; 不会返回任何 json 值。

查询 -$query = "SELECT * FROM states where Continental_code='AS'"; 正确返回 json 值。

$query = "SELECT * FROM states where Continental_code='EU'"; 也不会返回任何内容。

同样,“NA”、“AF”不起作用,而其他则完美。

我对 PHP json_encode 的这种行为感到很奇怪。

这是我的代码。

<?php
$con=mysqli_connect('localhost','xxxx','xxxxx','joomla30');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM countries where continent_code='EU'") or die (mysqli_error($con));

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$orders[] = array(
'CountryCode' => $row['code'],
'CountryName' => $row['name']
);
}
//print_r($orders);

echo json_encode($orders);

mysqli_close($con);
?>

直到上一行json_encode,数据才被携带。所以我认为它的json编码问题。

我尝试使用print_r($orders);来了解它。
我从中得到了以下输出。

如果我尝试输入“EU”,我会得到这个数组。

Array ( [0] => Array ( [CountryCode] => AD [CountryName] => Andorra ) 
[1] => Array ( [CountryCode] => AL [CountryName] => Albania )
[2] => Array ( [CountryCode] => AT [CountryName] => Austria )
[3] => Array ( [CountryCode] => AX [CountryName] => Åland Islands )...

如果我尝试输入“AS”,我会得到这个数组。

Array ( [0] => Array ( [CountryCode] => AE [CountryName] => United Arab Emirates ) 
[1] => Array ( [CountryCode] => AF [CountryName] => Afghanistan)
[2] => Array ( [CountryCode] => AM [CountryName] => Armenia)
[3] => Array ( [CountryCode] => AZ [CountryName] => Azerbaijan)...

两个数组看起来很相似,对吧...但 Json_encode 仅适用于“AS”,不适用于“EU”。

有谁知道如何解决这个问题吗?如果是这样,请告诉我..

最佳答案

您应该确保 Web 应用程序的每个组件都使用 UTF-8。 This answer另一个问题会告诉你如何做到这一点。如果你read this来自 RFC4627:

Encoding: JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.

json_encode 函数要求所有传入数据都采用 UTF-8 编码。这就是为什么ÅlandIslands之类的字符串可能会给您带来问题。

关于php json_encode 部分不适用于数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19999665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com