Please have a quick read of this question first: Separating a list of entries by the first letter in a given field
Onto the main body of the question.
I am trying to sort several titles in a given array. Currently, they are echoed out alphabetically, however, the current code does not achieve one other aim: to display the alphabetical letter for its grouping. Example below:
A
=====================================
- Alice's Adventured in Wonderland
- Animal Farm
B
=====================================
- Beyond the Chocolate War
and so forth.
Current, the code displays as so:
Alice's Adventured in Wonderland
Animal Farm
Beyond the Chocolate War
As you can see, I need to now categorise by Alphabetic letters. Another example of the HTML output is seen here: http://wiki.solusvm.com/index.php/Category:Documentation (note that I only need it to display category + titles like that, HTML output)
Here's the code I've got so far:
<?php
function shamil_title_compare($a, $b) {
return strcasecmp($a['title'], $b['title']);
}
usort($entries, 'shamil_title_compare');
$alphabetized = array();
foreach (range('A', 'Z') as $letter) {
$alphabetized[开发者_开发问答$letter] = array();
}
foreach ($entries as $entry) {
$title = $entry['title'];
$firstWord = strtok($title, ' ');
if (!in_array($firstWord, array('The', 'A'))) {
$alphabetized[$firstWord[0]][] = $entry;
} else {
$nextWord = strtok(' ');
if ($nextWord !== false) {
$alphabetized[$nextWord[0]][] = $entry;
} else {
$alphabetized[$firstWord[0]][] = $entry;
}
}
echo $entry['title']."<br/>";
}
What do I do now?
I would add each new letter to an array right before echo $entry['title']."<br/>";
$letter = substr($entry['title'],0,1);
if(!in_array($letter, $lettersArray) || count($lettersArray) == 0){
array_push($lettersArray,$letter);
echo $letter.'<p><hr /></p>';
}
echo $entry['title']."<br/>";
This checks to see if the letter is already in the array, if not it adds it and prints it out.
精彩评论