Group Your Results with PHP
Tuesday, June 17th, 2008
While working on a personal project this evening, I wrote a small function to group a list of results by the first letter of each record.
As simple as it may be, I think it’s very effective in breaking up a long list of results and it’s very easy to implement.
First up I defined a list of names in an array, and then sorted them alphabetically.
-
$contacts = array(‘John’, ‘Peter’, ‘Adam’, ‘Sam’, ‘Dick’, ‘Nicholas’, ‘Philip’, ‘Andrew’, ‘Thomas’, ‘Bruce’, ‘Steven’, ‘Brian’, ‘Terrence’);
Next I created a function called ‘group_by_first’. Here’s my code, I’ll explain what’s going on underneath.
-
function group_by_first($contact_name) {
-
global $cur_first;
-
if ($cur_first != $get_first) {
-
$cur_first = $get_first;
-
}
-
}
Line 1: Here we name the function and add a parameter that stores the current record
Line 2: Creating a global variable named $cur_first (current first letter), which will be empty to start with
Line 3: Here I define a variable called $get_first, and retrieve the first character from the current record. For example, if we’re on ‘Bruce’ then $get_first will store ‘B’
Line 4: Comparing the current letter group we’re in with the first letter of the current record. If they don’t match, that means we’ve run out of records that begin with that letter and we’re ready to make a new group
Line 5: Echo out a div with some styling, and the first letter of the current record. The inline CSS is there purely for demonstration, please rememeber to define a class in your stylesheet!
Line 6: We’ve added a new group, so now we’ve got to tell $cur_first that we’re on the next letter in the list, which we do by assigning it the value of $get_first
Line 8: Finally, we echo out the current record
All we’ve got left to do now is to run each element of the array through our function!
-
foreach ($contacts as $value) {
-
group_by_first($value);
-
}
And here’s a basic example of it in action.
With some better styling I think that this can be an elegant solution for breaking up your lists of records.
