Sorting method with Chinese in php array
- 2021-06-28 11:39:57
- OfStack
Chinese sorting of php array, file format 1 is usually utf8, not directly using asort.If gbk and gb2312 can.This is about coding.The codes of gbk and gb2312 themselves are sorted in phonetic order.
Example use:
However, using this function, it is found that some words may be wrong, possibly because the utf8 encoding does not recognize some words resulting in "illegal characters". It is known that the GBK character set is large, replaced by GBK, plus IGNORE ignores unknown characters and replaces them with the following
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;
}
Example use:
$abc = array('a'=>' guess ', 'b'=>' I ','c'=>' Oh ','d'=>' stick ','e'=>'f','f'=>' dad ','z'=>' State ');
utf8_array_asort($abc);
print_r($abc);
However, using this function, it is found that some words may be wrong, possibly because the utf8 encoding does not recognize some words resulting in "illegal characters". It is known that the GBK character set is large, replaced by GBK, plus IGNORE ignores unknown characters and replaces them with the following
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;
}