Slim 框架数组未在 JSON 中编码
Slim framework array is not encoding in JSON
我有一个数组,我正在使用 withJson() 在 JSON 中编码,但它抛出了 slim 应用程序错误。
下面是我的代码和数组值:
$db = Db::get_instance();
$stmt = $db->query($sql);
if($stmt->rowCount() > 0)
{
$dataList = $stmt->fetchAll(PDO::FETCH_ASSOC);
//print_r($dataList);die;
}
$data = array();
foreach($dataList as $row)
{ //print_r($row);
$id = '';
$name = '';
foreach($row as $key=>$value)
{
if($key == 'id') $id = $value;
if($key == 'countname') $countname = trim($value);
if($key == 'city') $city = trim($value);
if($key == 'region') $region = trim($value);
if($key == 'type')
{
if($value == 'country') $name="$countname ($value)";
if($value == 'state') $name = "$region, $countryname ($value)";
if($value == 'city') $name="$city,$region,$countname ($value)";
}
//$name = str_replace(',',' ',$name);
$temp['id'] = $id;
$temp['name'] = $name;
}
$data[] = $temp;
}print_r($data);die;
return $response->withJson($data,200);
请注意我的数组中有一些特殊字符:[7] => 数组
(
[编号] => 4634
[名称] => Saint-g�rard,Belgium(城市)
)
我的数组如下:
Array
(
[0] => Array
(
[id] => 65
[name] => Ura Vajgurore,,Albania (city)
)
[1] => Array
(
[id] => 2024
[name] => Birregurra,,Australia (city)
)
[2] => Array
(
[id] => 2703
[name] => Kallangur,,Australia (city)
)
[3] => Array
(
[id] => 985
[name] => Gurnitz,,Austria (city)
)
)
正如您提到的,我的 array
数据中有特殊字符:
示例:
[7] => Array
(
[id] => 4634
[name] => Saint-gÚrard,,Belgium (city)
)
您必须在建立数据库连接后重置常量名称:
$db = Db::get_instance();
$db->exec("SET NAMES 'utf8';");
希望这对你有用。
我有一个数组,我正在使用 withJson() 在 JSON 中编码,但它抛出了 slim 应用程序错误。 下面是我的代码和数组值:
$db = Db::get_instance();
$stmt = $db->query($sql);
if($stmt->rowCount() > 0)
{
$dataList = $stmt->fetchAll(PDO::FETCH_ASSOC);
//print_r($dataList);die;
}
$data = array();
foreach($dataList as $row)
{ //print_r($row);
$id = '';
$name = '';
foreach($row as $key=>$value)
{
if($key == 'id') $id = $value;
if($key == 'countname') $countname = trim($value);
if($key == 'city') $city = trim($value);
if($key == 'region') $region = trim($value);
if($key == 'type')
{
if($value == 'country') $name="$countname ($value)";
if($value == 'state') $name = "$region, $countryname ($value)";
if($value == 'city') $name="$city,$region,$countname ($value)";
}
//$name = str_replace(',',' ',$name);
$temp['id'] = $id;
$temp['name'] = $name;
}
$data[] = $temp;
}print_r($data);die;
return $response->withJson($data,200);
请注意我的数组中有一些特殊字符:[7] => 数组 ( [编号] => 4634 [名称] => Saint-g�rard,Belgium(城市) )
我的数组如下:
Array
(
[0] => Array
(
[id] => 65
[name] => Ura Vajgurore,,Albania (city)
)
[1] => Array
(
[id] => 2024
[name] => Birregurra,,Australia (city)
)
[2] => Array
(
[id] => 2703
[name] => Kallangur,,Australia (city)
)
[3] => Array
(
[id] => 985
[name] => Gurnitz,,Austria (city)
)
)
正如您提到的,我的 array
数据中有特殊字符:
示例:
[7] => Array
(
[id] => 4634
[name] => Saint-gÚrard,,Belgium (city)
)
您必须在建立数据库连接后重置常量名称:
$db = Db::get_instance();
$db->exec("SET NAMES 'utf8';");
希望这对你有用。