我从我的MySQL数据库收到一个多维数组
Array
(
[0] => Array
(
[page] => categorypropose
[value] => baby-sitters
[id] => 357960
)
[1] => Array
(
[page] => categorysearch
[value] => adéquate pour garder
[id] => 357961
)
...
)
在这个数组中,我有一些 ISO-8859-1 到 UTF8 的转换,可以通过"自制"函数"加载文本"来完成。
但是当我这样做时:
$array = $query->result_array();
foreach($array as &$k)
{
foreach ($k as &$value)
{
//Works
$value = $this->loadtext($value, 'ISO-8859-1');
}
}
//Back to normal as $this->loadtext never existed
print_r($array);
它不保留更改(当我回显$value时,它可以工作,但修改不会保留在最后......
编辑:这是我有义务使用的函数加载文本(实际上,我没有成功,但我必须使用它......
function loadtext($text,$charset){
$text = stripslashes($text);
if($charset!="UTF-8")
$text = iconv("UTF-8",$charset,$text);
$text = str_replace(" :"," :",$text);
$text = str_replace(" ;"," ;",$text);
$text = str_replace(" !"," !",$text);
$text = str_replace(" ?"," ?",$text);
$text = str_replace(" ."," .",$text);
$text = str_replace(" …"," …",$text);
return $text;
}
你可以这样尝试:
$array = $query->result_array();
foreach($array as &$k)
{
foreach ($k as $i => &$value)
{
//Works
$k[$i] = $this->loadtext($value, 'ISO-8859-1');
}
}
//Back to normal as $this->loadtext never existed
print_r($array);
但更好的是,您可以尝试在查询中使用 MySQL 函数CONVERT()
,以便您返回的字符串已经采用 UTF8 格式。
http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html
至少,使用 PHP 的 mb_convert_encoding()
而不是自制函数。没有理由重新发明轮子。
http://jp2.php.net/manual/en/function.mb-convert-encoding.php
我自己找到了一个简单的答案,这对我来说非常有效,因为我使用 php 中的另一种方法来更改我从 mysql 结果中获得的值
// ur array from mysql
$array = $query->result_array();
//try it works 100 % for me just one line of code to modify
$result= iconv('UTF-8', 'ASCII//TRANSLIT',$array);
来源 : php.net
// or if doesnt work then u can try like this to modify u can put it inside a foreach loop where you are loopin values
$page = array['page']; // to acces that element in the array where to modify
$result= iconv('UTF-8', 'ASCII//TRANSLIT',$page);
我突然想到,这个特定问题还有另一种解决方案,可以完全避免通过引用修改数组的问题。
$array = array_map(function ($row) {
return array_map(function ($col) { return mb_convert_encoding($col, 'ISO-8859-1'); }, $row);
}, $query->result_array());
这使用匿名函数,这些函数仅在 PHP 5.3 之后可用,因此,如果您有较旧的东西,则必须以不同的方式实现它,这可能不值得麻烦,但我认为这是一个很好的方法。
此外,这样做可能会更有效/看起来更干净:
$colFn = function ($col) { return mb_convert_encoding($col, 'ISO-8859-1'); };
$rowFn = function ($row) use ($colFn) { return array_map($colFn, $row); };
$array = array_map($rowFn, $query->result_array());