Home > Backend Development > PHP Tutorial > Sorting method containing Chinese in php array_PHP tutorial

Sorting method containing Chinese in php array_PHP tutorial

WBOY
Release: 2016-07-13 10:29:01
Original
731 people have browsed it

PHP array Chinese sorting, file format generally uses utf8, direct sorting using asort will not work. If gbk and gb2312 are available. This has to do with coding. The coding of gbk and gb2312 itself is sorted by pinyin.

Copy code 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', 'GB2312',$v);
}
asort($array);
foreach($array as $k=>$v) {
$array[ $k] = iconv('GB2312', 'UTF-8', $v);
}
return true;
}

Usage example:
Copy code The code is as follows:

$abc = array('a'=>'guess', 'b'=>'I', 'c'=>'Oh','d'=>'stick','e'=>'f','f'=>'Dad','z'=>'zhou') ;
utf8_array_asort($abc);
print_r($abc);

However, using this function, I found that some text will be wrong. It may be that the utf8 encoding does not recognize some characters, causing "illegal" Characters", it is understood that the GBK character set is relatively large, so change it to GBK, plus IGNORE ignores unknown characters, and change it to the following
Copy code The code is as follows:

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/779575.htmlTechArticlePHP array Chinese sorting, the file format is generally utf8, direct sorting with asort will not work. If gbk and gb2312 are available. This has to do with coding. The coding of gbk and gb2312 itself is sorted by pinyin. ...
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