dongxianglun5163 2019-03-09 23:15
浏览 104
已采纳

PHP按自定义顺序排序三个字母字符

I'm trying to sort groups of three characters like LMH, MMH, HHL etc all containing only the characters L, M and H but I need them sorted in the order LMH. This is what I have but not sure how to compare them. The $val array doesn't work when there are duplicate characters. It's a string that is broken into an array by the function.

function sortit($str) {
 $val = ['L' => 0, 'M' => 1, 'H' => 2];
 $parts = str_split($str);
 foreach ($parts as $value) {
   $order[$val[$value]] = $value;
 }
 ksort($order);
 return implode('',$parts);
 }

Input:

MLH 
HLL 
MHM 
LHM 
MLH 
LHM 
MHL

Desired output:

LMH 
LLH 
MMH 
LMH 
LMH 
LMH 
LMH
  • 写回答

2条回答 默认 最新

  • dsdzz04802 2019-03-09 23:35
    关注

    Use usort doc:

    function sortit($str) {
       $val = ['L' => 0, 'M' => 1, 'H' => 2];
       $parts = str_split($str);
       usort($parts, function ($a, $b) use ($val) {return $val[$a] - $val[$b];});
       return implode("", $parts);
     }
    

    Use it as:

    echo sortit("MLH"); // output LMH 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 根据历年月数据,用Stata预测未来六个月汇率
  • ¥15 DevEco studio开发工具 真机联调找不到手机设备
  • ¥15 请教前后端分离的问题
  • ¥100 冷钱包突然失效,急寻解决方案
  • ¥15 下载honeyd时报错 configure: error: you need to instal a more recent version of libdnet
  • ¥15 距离软磁铁一定距离的磁感应强度大小怎么求
  • ¥15 霍尔传感器hmc5883l的xyz轴输出和该点的磁感应强度大小的关系是什么
  • ¥15 vscode开发micropython,import模块出现异常
  • ¥20 Excel数据自动录入表单并提交
  • ¥30 silcavo仿真,30分钟,只需要代码