I have a wordpress site (still in development on my localhost, sorry I can't provide a link) that provides definitions and explanations for common 6th grade math concepts. The main part of the site is a concept map or web, but my boss also wants us to provide a functionality to browse the terms alphabetically, like a dictionary or index.
So what she wants is commonly available on the web: All the terms that start with A listed under 'A', all the terms that start with B listed under 'B', etc. I can retrieve all the terms from the database and sort them, but I am unsure of the best way to display them.
Example: The web page should look like this:
A
• apple
• artichoke
• avocado
B
• banana
• blueberry
etc.
I am thinking that I could build the HTML framework, and within each letter's div query the database for all the terms that start with that letter. Like this (in psuedocode):
<div id='a-section'>
<?php $terms=$wpdb->get_results("all terms that start with A");
foreach( $terms as $term ) { ?>
<a link-to-definition><?php echo $term ?></a>
<?php } ?>
</div>
<div id='b-section'>
....
For this, I would need 26 queries to the database, so I am thinking this method would be fairly inefficient. Can I do better? What if I retrieved all the terms in one query, sorted them alphabetically, and looked at the first letter of each term? Would that work? It seems a while( "a" == first-letter-of-$term )
may not work inside the foreach( $results as $term )
, since the foreach loop will only execute once for each $term. But I don't really want to write 26 (27, actually, since some terms start with numerals) if( "a" == first-letter-of-$term )
statements inside the foreach loop.
I hope I've explained this dilemma clearly. Can anyone suggest how I should proceed? I would think someone has done something like this, but google didn't help me find any answers. Thanks in advance.
$glossary_letter != $term_letter
which is where you print the next starting letter before listing the terms that start with that letter