PHP 取字符串中第一个字的首字母,根据字符串首字母排序方法:
/**
* 取汉字首字母
* @param string $str 字符串
*/
function getStrOne($str){
if(empty($str)) return '';
$fchar = ord($str{0});
if($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str{0});
$s1 = iconv('UTF-8','GB2312//TRANSLIT//IGNORE',$str);
$s2 = iconv('GB2312','UTF-8//TRANSLIT//IGNORE',$s1);
$s = $s2==$str ? $s1 : $str;
$asc = @ord($s{0})*256+@ord($s{1})-65536;
if($asc>=-20319 && $asc<=-20284) return 'A';
if($asc>=-20283 && $asc<=-19776) return 'B';
if($asc>=-19775 && $asc<=-19219) return 'C';
if($asc>=-19218 && $asc<=-18711) return 'D';
if($asc>=-18710 && $asc<=-18527) return 'E';
if($asc>=-18526 && $asc<=-18240) return 'F';
if($asc>=-18239 && $asc<=-17923) return 'G';
if($asc>=-17922 && $asc<=-17418) return 'H';
if($asc>=-17417 && $asc<=-16475) return 'J';
if($asc>=-16474 && $asc<=-16213) return 'K';
if($asc>=-16212 && $asc<=-15641) return 'L';
if($asc>=-15640 && $asc<=-15166) return 'M';
if($asc>=-15165 && $asc<=-14923) return 'N';
if($asc>=-14922 && $asc<=-14915) return 'O';
if($asc>=-14914 && $asc<=-14631) return 'P';
if($asc>=-14630 && $asc<=-14150) return 'Q';
if($asc>=-14149 && $asc<=-14091) return 'R';
if($asc>=-14090 && $asc<=-13319) return 'S';
if($asc>=-13318 && $asc<=-12839) return 'T';
if($asc>=-12838 && $asc<=-12557) return 'W';
if($asc>=-12556 && $asc<=-11848) return 'X';
if($asc>=-11847 && $asc<=-11056) return 'Y';
if($asc>=-11055 && $asc<=-10247) return 'Z';
return '~';
}使用案例:
//比如执行数据库查询语句得到数据如下:(SELECT * FROM `article`)
$data = [
['id'=>1, 'name'=>'吧吧吧吧吧吧'],
['id'=>2, 'name'=>'啊啊啊啊啊啊'],
['id'=>3, 'name'=>'怕怕怕怕怕怕'],
['id'=>4, 'name'=>'人人人人人人'],
];
// 根据name的第一个字的首字目来升序排序
$w = [];
foreach ($data as $k =>$v) {
$data[$k]['key'] = getStrOne($v['name']);
$w[$k] = getStrOne($v['name']);
}
array_multisort($w,SORT_STRING,SORT_ASC,$data);
print_r($data);结果:
Array ( [0] => Array ( [id] => 2 [name] => 啊啊啊啊啊啊 ) [1] => Array ( [id] => 1 [name] => 吧吧吧吧吧吧 ) [2] => Array ( [id] => 4 [name] => 人人人人人人 ) [3] => Array ( [id] => 3 [name] => 怕怕怕怕怕怕 ) )
转载请注明来源地址:小川编程 » https://www.youhutong.com/index.php/article/index/140.html
1、本站发布的内容仅限用于学习和研究目的.请勿用于商业或非法用途,下载后请24小时内删除。
2、本站所有内容均不能保证其完整性,不能接受请勿购买或下载,如需完整程序,请去其官方购买正版使用
3、本站联系方式Email:admin@youhutong.com ,收到邮件会第一时间处理。
4、如侵犯到任何版权问题,请立即告知本站(立即在线告知),本站将及时删除并致以最深的歉意
