UTF8 Chinese sorting sample code in PHP and MYSQL, _PHP tutorial

WBOY
Release: 2016-07-13 10:16:23
Original
771 people have browsed it

UTF8 Chinese sorting sample code in PHP and MYSQL,

1. It is necessary to sort in Chinese 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.

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;
}

Copy after login

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.jb51.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:
For fields containing Chinese, add the "binary" attribute 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

The code is as follows

Copy code The code is as follows:

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/898279.htmlTechArticle UTF8 Chinese sorting sample code in PHP and MYSQL, 1. It is necessary to use Chinese sorting in PHP arrays, but it is generally used Files in utf8 format cannot be sorted directly using asort. You can use gbk and gb2312. ...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template