php - Sort array of strings by 3rd-to-last character based on another array then sort on whole strings
144
I have an array like:
$unsorted = Array(
"0" =>"3470U11",
"1" =>"3470E11",
"2" =>"3470S13",
"3" =>"3470G11",
"4" =>"3470S12",
"5" =>"3470S11",
"6" =>"3470E12",
"7" =>"3470U12",
"8" =>"3470G13",
"9" =>"3470G12",
"10" =>"3470E13",
"11" =>"3470U13"
);
And a priority array like this:
$sortBy = array('G','D','S','U','E','T','A','L');
I need to sort the array by thesubstr($value,-3,1)
in the order listed in$sortBy
so the result becomes like:
$sorted = Array(
"0" => "3470G11",
"1" => "3470G12",
"2" => "3470G13",
"3" => "3470S11",
"4" => "3470S12",
"5" => "3470S13",
"6" => "3470U11",
"7" => "3470U12",
"8" => "3470U13",
"9" => "3470E11",
"10" =>"3470E12",
"11" =>"3470E13"
);
Answer
Solution:
usort
(PHP 4, PHP 5, PHP 7) usort — Sort an array by values using a user-defined comparison function
Answer
Solution:
You can use a user defined compare function when sorting. usort() if you want the indexes to be rearanged or uasort() if you want to keep the keys as they are.
Your callback function can be something like this:
See on php.net:
Answer
Solution:
Try to someting like this....
Answer
Solution:
Assuming:
This is a concise, accurate, modern, professional way to implement the required sorting. I am calling
usort()
which first sorts on the third-last letter based on the original index of the$sortBy
array. The "Elvis operator" (?:
) separates the first rule from the second rule. The whole string comparision is the fallback sorting rule if the first rule results in a tie.Code: (Demo)
Output:
Answer
Solution:
try this : PHP usort() will the suitable for that
OUTPUT
Answer
Solution:
try this instead