TL;DR: I need to sort an array of specific words. The order should match an existing array. See the example code in the last code block.
I have an array of titles, the first word of each title is a color. I'm used to sorting arrays at this point, but this one is confusing.
The problem: I need to manually sort an array of words based on a list of words that is already sorted. I have uasort
set up so that I have the following two variables ready for the comparison:
// first comparison:
$a_first = strtolower( $a_split[0] ); // white
$b_first = strtolower( $b_split[0] ); // blue
// 2nd comparison:
$a_first = strtolower( $a_split[0] ); // purple
$b_first = strtolower( $b_split[0] ); // white
// 3rd comparison:
$a_first = strtolower( $a_split[0] ); // blue
$b_first = strtolower( $b_split[0] ); // purple
I need to sort these colors by belt ranking, for a jiu-jitsu ranking system. Here is the array in the correct order:
$color_order = explode(' ', 'white blue purple brown black black-red coral white-red red');
/* $color_order =
Array (
[0] => white
[1] => blue
[2] => purple
[3] => brown
[4] => black
[5] => black-red
[6] => coral
[7] => white-red
[8] => red
)
Current (incorrect) results:
1. Blue
2. Purple
3. White
Desired results:
1. White
2. Blue
3. Purple
*/
My current code, which comes out of uasort(), sorting alphabetically with strcmp. I need to replace strcmp with something that can sort using my color array. (Fyi, colors do not match the word, they are moved to a different array - so I don't need error checking in here).
// Sort Step 1: Sort belt level by color
// $video_categories[belt_id][term]->name = "White belt example"
function _sort_belt_names( $a, $b ) {
$a_name = trim( $a['term']->name );
$b_name = trim( $b['term']->name );
$a_split = explode( ' ', $a_name );
$b_split = explode( ' ', $b_name );
if ( $a_split && $b_split ) {
$color_order = explode(' ', 'white blue purple brown black black-red coral white-red red');
// IMPORTANT STUFF BELOW! ----
$a_first = strtolower( $a_split[0] ); // purple
$b_first = strtolower( $b_split[0] ); // white
// Compare $a_first $b_first against $color_order
// White should come first, red should come last
// Return -1 (early), 0 (equal), or 1 (later)
// IMPORTANT STUFF ABOVE! ----
}
// If explode fails, sort original names alphabetically.
return strcmp( $a_name, $b_name );
}
// ---
uasort( $video_categories, '_sort_belt_names' );
belt_id
in$video_categories[belt_id]
? Isn't it the color id? So you could sort by that.. – bitWorking Jul 22 '13 at 23:16