Saturday, April 30, 2011

PHP To Loop Through Alphabet & Display Categories

The alphabet can be incremented in PHP like numbers can, so incrementing through an alphabetical list is possible.

$capital="A";
$capital++;
echo $capital;
(returns b)

To write all 26 letters of the alphabet
$capital=A;
for ($i=1; $i<=26; $i++)
{
echo $capital;
$capital++;
}
(returns whole alphabet)

I wanted to display categories, in divs, in alphabetical order, querying a database to get categories beginning with each letter, to display in the div corresponding to that letter.

It ends up looking like this...



I set css properties for the divs as follows..
.prop{
height:200px;
float:right;
width:1px;
display:inline;
padding:5px;
margin:5px;
float:left;
width:160px;
border-style:solid;
border-width:2px;
border-color:#2491EE;
}

The php I did as follows...


$capital=A;
for ($i=1; $i<=26; $i++)

{
/*echoes the current letter, images could be used if named A.jpg B.jpg etc*/

echo "<div class=\"prop\"> <strong>".$capital."</strong><br />";

/*The mysql quries a category table returning all categories beginning the current letter*/
$result=mysql_query("SELECT category FROM categories WHERE category REGEXP '^".$capital."' ORDER BY category") or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$cat= $row['category'];

/*the following line echoes the category name and links to a category page, passing the name as a variable*/
echo "<a href='category.htm?category=$cat'>".$cat."</a><br />";
}
echo "</div>";
$capital++;
}

2 comments:

Chethi said...

Hi..chandrika.
my name is Chethan,im a web developer.Today i go through ur blog,its really cool and awesome and i c ur tutorial for php loop through the alphabits and display categories.actually i wannt to disply products like in this link provided:http://www.citizen.com.hk/en/customer-support/warranty-registration#top
so can u please help me how to do this.
with hopes....
thanks &Regards
Chethan

Chandrika Gauranga dasi said...

Hi Chetan, that is a nice product display, with the sub categories and then the 5 columns with products in order. I guess jquery is used for the show/hide within categories.

Do you have your products in a mysql database, or some kind of datafeed file (xml,csv,etc)?