Home >Backend Development >PHP Tutorial >UTF8 Chinese sorting example in PHP and MYSQL, _PHP tutorial
1. It is necessary to use Chinese sorting in the PHP array, but files in UTF8 format are generally used, and direct sorting with asort will not work. You can use gbk and gb2312. This has something to do with the encoding of several formats. The coding of gbk and gb2312 itself is sorted by pinyin.
Copy the code as follows
function utf8_array_asort(&$array)
{
if(!isset($array) || !is_array($array))
{
return false ;
}
foreach($array as $k=>$v)
{
$array[$k] = iconv('UTF-8', 'GBK//IGNORE', $v);
}
asort($array);
foreach($array as $k=>$v)
{
$array[$k] = iconv(' GBK', 'UTF-8//IGNORE', $v);
}
return true;
}
2. In MySQL, we often sort and query a field, but when sorting and searching in Chinese, the sorting and search results of Chinese characters are often wrong. This situation exists in many versions of MySQL (www.111cn.net).
If this problem is not solved, then MySQL will not be able to actually handle Chinese. The reason for this problem is that MySQL is not case-sensitive when querying strings. When compiling MySQL, the ISO-8859 character set is generally used as the default character set. Therefore, the case conversion of Chinese coded characters occurs during the comparison process. this phenomenon.
Solution:
Add the "binary" attribute to the field containing Chinese to make it a binary comparison, for example, change "name char(10)" to "name char(10)binary".
If you use source code to compile MySQL, you can use the --with--charset=gbk parameter when compiling MySQL, so that MySQL will directly support Chinese search and sorting (the default is latin1). You can also use extra-charsets=gb2312,gbk to add multiple character sets.
If you do not want to modify the table structure or recompile MySQL, you can also use the CONVERT function in the order by part of the query statement. For example
Copy the code as follows
select * from mytable order by CONVERT(chineseColumnName USING gbk);
from:http://www.111cn.net/phper/php-cy/67815.htm