我正在尝试使用json_encode对对象数组进行编码,但如果它遇到像Ñ这样的特殊字符,它会为该字段提供一个空值。
我能够使用utf8_encode
将2个字符串编码为uft8
主要问题是我无法使用utf8_encode
对数组进行编码。你能帮我解决这个问题吗?
这是我的剧本:
Mysql查询
$consulta = "SELECT id AS nrocliente, empresa, nombre, tipodoc, doc, email, tel, cel, nombrealt, calle, numero, piso, depto, localidad, prov, codpostal FROM envio_clientes";
$result = mysqli_query($db, $consulta);
创建对象数组
//Se crea un array con todos los resultados
$cities = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$cities[] = array ( 'nrocliente' => $row['nrocliente'], 'empresa' => $row['empresa'], 'nombre' => $row['nombre'], 'tipodoc' => $row['tipodoc'], 'doc' => $row['doc'], 'email' => $row['email'], 'tel' => $row['tel'], 'cel' => $row['cel'], 'nombrealt' => $row['nombrealt'], 'calle' => $row['calle'], 'numero' => $row['numero'], 'piso' => $row['piso'], 'depto' => $row['depto'], 'localidad' => $row['localidad'], 'prov' => $row['prov'], 'codpostal' => $row['codpostal'] );
}
获取jQuery自动填充术语
// Cleaning up the term
$term = trim(strip_tags($_GET['term']));
// Rudimentary search
$matches = array();
创建一个稍后将由json_encode处理的新数组
foreach($cities as $city){
if(stripos($city['nombre'], $term) !== false){
// Add the necessary "value" and "label" fields and append to result set
$city['value'] = utf8_encode($city['nombre']);
//$city['label'] = "{$city['nombre']} {$city['localidad']}, {$city['nrocliente']}";
$city['label'] = utf8_encode("{".$city['nombre']."} {".$city['localidad'] ."} {". $city['nrocliente']. "}");
$matches[] = $city;
}
}
请注意:在上面的代码中,$city['label']
和$city['value']
使用utf8_encode
处理得很好。
json_encode流程
// Truncate, encode and return the results
$matches = array_slice($matches, 0, 5);
print json_encode($matches);
?>
这就是我的回应:
{"nrocliente":"2","empresa":"Medicas SRL","nombre":null,"tipodoc":"DNI","doc":"000000000","email":"","tel":"2223332222","cel":"","nombrealt":"","calle":"Av. Frey","numero":"222","piso":"","depto":"","localidad":"Capital","prov":"Santa Fe","codpostal":"3000","value":"Ivan \u00d1ibazeta","label":"{Ivan \u00d1ibazeta} {Capital} {2}"}]
请注意:字段nombre
为空,但value
和label
显示相当于Ñ字符。
我应该怎样做才能将utf8_encode
应用于$cities
数组或$matches
数组?
提前致谢!