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
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
$val = ['L' => 0, 'M' => 1, 'H' => 2];
$strings = ['HML', 'MHM', 'LHL'];
foreach ($strings as $str) {
$arr = str_split($str);
usort($arr, function($val1, $val2) use ($val) {
return $val[$val1] <=> $val[$val2];
});
var_dump(implode('', $arr));
}
You can sort it with usort and a custom compare function. Here I used your val array, which was a good first idea.