Home >Backend Development >PHP Tutorial >php数组中包含中文的排序方法_PHP

php数组中包含中文的排序方法_PHP

WBOY
WBOYOriginal
2016-06-01 11:52:391098browse

php数组中文排序,文件格式一般用utf8,直接用asort排序不行。若是gbk和gb2312可以。这跟编码有关。gbk和gb2312本身的编码就是用拼音排序的。
复制代码 代码如下:
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;
}
使用例子:
复制代码 代码如下:
$abc = array('a'=>'猜', 'b'=>'我','c'=>'哦','d'=>'棍','e'=>'f','f'=>'爸','z'=>'州');
utf8_array_asort($abc);
print_r($abc);
但是使用这个函数发现,有些文字会出错,可能是utf8编码认不出某些字导致的“非法字符”,据了解GBK字符集比较大,换成GBK,再加上IGNORE忽略掉不认识的字符 ,改成下面这样
复制代码 代码如下:
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;
}

Statement:
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