Created
May 1, 2015 22:41
-
-
Save dydx/48957e5bfe3a7082d9f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// unordered list | |
$list = Array( | |
0 => 'My Images', | |
1 => 'Text Alignment', | |
2 => 'Your New Post', | |
3 => 'The More Tag', | |
4 => 'The Average Post', | |
5 => 'The Paginated' | |
); | |
// Desired output: | |
// Array( | |
// 4 => 'The Average Post', | |
// 3 => 'The More Tag', | |
// 0 => 'My Images', | |
// 5 => 'The Paginated', | |
// 1 => 'Text Alignment', | |
// 2 => 'Your New Post' | |
// ) | |
function alphabetical_sort_with_initial_articles($array) { | |
$temp_results = []; | |
$results = []; | |
foreach($array as $key => $value) { | |
$value_arr = explode(' ', $value); | |
if($value_arr[0] === 'The') { // need to make this dynamic: the|The|etc. | |
$initial_article = array_shift($value_arr); | |
$temp_results[$key] = array( | |
implode(' ', $value_arr), | |
$initial_article | |
); | |
} else { | |
$temp_results[$key] = array( | |
implode(' ', $value_arr), | |
false | |
); | |
} | |
} | |
uasort($temp_results, function($a, $b) { | |
return ($a[0] > $b[0]); | |
}); | |
foreach($temp_results as $key => $value) { | |
$results[$key] = trim($value[1] . ' ' . $value[0]); | |
} | |
return $results; | |
} | |
print_r($list); | |
echo "------------------------\n"; | |
print_r(alphabetical_sort_with_initial_articles($list)); | |
//josh@lear:~/Development/PHP/$ time php lists.php | |
//Array | |
//( | |
// [0] => My Images | |
// [1] => Text Alignment | |
// [2] => Your New Post | |
// [3] => The More Tag | |
// [4] => The Average Post | |
// [5] => The Paginated | |
//) | |
//------------------------ | |
//Array | |
//( | |
// [4] => The Average Post | |
// [3] => The More Tag | |
// [0] => My Images | |
// [5] => The Paginated | |
// [1] => Text Alignment | |
// [2] => Your New Post | |
//) | |
// | |
//real 0m0.032s | |
//user 0m0.017s | |
//sys 0m0.013s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment