Example code of UTF8 Chinese sorting in PHP and MYSQL

  • 2021-07-22 09:15:30
  • OfStack

1. Need in the php array with Chinese sorting, but 1 general use of utf8 format files, directly with asort sorting is not good. You can use gbk and gb2312. This is related to the coding of several formats. The codes of gbk and gb2312 themselves are sorted in pinyin.

The code is 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 Chinese characters, the sorting and searching results of Chinese characters are often wrong. This is the case in many versions of MySQL (www. ofstack. com).
If this problem is not solved, MySQL will not be able to actually process Chinese. The reason for this problem is that MySQL is case-insensitive when querying strings, and ISO-8859 character set is generally used as the default character set when compiling MySQL, so this phenomenon is caused by case conversion of Chinese encoded characters in the comparison process.
Solution:
Add the attribute "binary" to the fields containing Chinese for binary comparison, for example, change "name char (10)" to "name char (10) binary".
If you compile MySQL with source code, you can compile MySQL with the parameter -with-charset=gbk, 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 section of the query statement. For example

The code is as follows


select * from mytable order by CONVERT(chineseColumnName USING gbk);


Related articles: