Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dydx/48957e5bfe3a7082d9f0 to your computer and use it in GitHub Desktop.
Save dydx/48957e5bfe3a7082d9f0 to your computer and use it in GitHub Desktop.
<?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