我有一个数组:
require_once ('config.php');
require_once ('php/Db.class.php');
require_once ('php/Top.class.php');
echo "db";
$db = new Db(DB_CUSTOM);
$db->connect();
$res = $db->getResult("select first 1 * from reklamacje");
print_r($res);
我想将它从 windows-1250 转换为 utf-8,因为我有像 �
这样的字符最佳。
$utfEncodedArray = array_map("utf8_encode", $inputArray );
完成工作并返回带有数字键(不是关联)的序列化数组。
array_walk(
$myArray,
function (&$entry) {
$entry = iconv('Windows-1250', 'UTF-8', $entry);
}
);
如果是 PDO 连接,以下内容可能会有所帮助,但数据库应为 UTF-8:
//Connect
$db = new PDO(
'mysql:host=localhost;dbname=database_name;', 'dbuser', 'dbpassword',
array('charset'=>'utf8')
);
$db->query("SET CHARACTER SET utf8");
有个简单的方法
array_walk_recursive(
$array,
function (&$entry) {
$entry = mb_convert_encoding(
$entry,
'UTF-8',
'WINDOWS-1250'
);
}
);
你可以使用这样的东西:
<?php
array_walk_recursive(
$array, function (&$value)
{
$value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
}
);
?>
您可以将数组发送到此函数:
function utf8_converter($array){
array_walk_recursive($array, function(&$item, $key){
if(!mb_detect_encoding($item, 'utf-8', true)){
$item = utf8_encode($item);
}
});
return $array;
}
对我有用。
以前的答案对我不起作用:( 但这样没关系:)
$data = json_decode(
iconv(
mb_detect_encoding($data, mb_detect_order(), true),
'CP1252',
json_encode($data)
)
, true)
您可以使用
string utf8_encode( string $data )
功能来完成您想要的。它适用于单个字符串。您可以编写自己的函数,使用它可以在 utf8_encode 函数的帮助下转换数组。
由于这篇文章是一个很好的SEO站点,所以我建议使用内置函数“mb_convert_variables”来解决这个问题。它使用简单的语法。
mb_convert_variables('utf-8', 'original encode', array/object)
一个更通用的数组编码函数是:
/**
* also for multidemensional arrays
*
* @param array $array
* @param string $sourceEncoding
* @param string $destinationEncoding
*
* @return array
*/
function encodeArray(array $array, string $sourceEncoding, string $destinationEncoding = 'UTF-8'): array
{
if($sourceEncoding === $destinationEncoding){
return $array;
}
array_walk_recursive($array,
function(&$array) use ($sourceEncoding, $destinationEncoding) {
$array = mb_convert_encoding($array, $destinationEncoding, $sourceEncoding);
}
);
return $array;
}
简单的工作方式是:
array_map(callable $callback, array $array1, array $... = ?): array
//Example #1 Example of the function array_map()
<?php
function cube($n)
{
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>
$b 的输出是:
Array
(
[0] => 1
[1] => 8
[2] => 27
[3] => 64
[4] => 125
)
有关更多详细信息 src -> PHP: array_map - Manual
您可以执行以下操作,而不是使用递归来处理可能很慢的多维数组:
$res = json_decode(
json_encode(
iconv(
mb_detect_encoding($res, mb_detect_order(), true),
'UTF-8',
$res
)
),
true
);
这会将任何字符集转换为 UTF8,并保留数组中的键。因此,您可以一次性完成整个结果集,而不是使用
array_walk
“懒惰”地转换每一行。