Jump to content

Group words that start with the same letter


newb

Recommended Posts

I am trying to create a glossary, and I am not sure how to group the letters of the same words underneath each other.

 

Right now, it is appearing as this:

 

A

apple

A

animal

A

amazing

A

attention

A

aero

A

axiom

 

B

butt

B

butter

b

brilliant

 

but i need it to appear as this:

 

A

apple

amazing

attention

aero

axiom

 

B

butt

butter

brilliant

 

here is my code:

		$query = exec_mysql_query("SELECT *,substring(en,1,1) as term FROM translations WHERE substring(en,1,1) RLIKE '[$letter]' ORDER by en asc");
	while ($row = mysql_fetch_assoc($query)) {
	$term = $row['term'];
	$enterm = htmlentities($row['en']);
	$esterm = htmlspecialchars($row['es']);
	$alt = htmlentities($row['alt']);
	$notes = htmlentities($row['notes']);


		if ($term == substr($enterm,0,1)) {
		echo "<b>$term</b><br />";
		echo "$enterm - $esterm - $alt - $notes<br />";
		}

	}
}

 

 

any ideas how i can fix this?

Here's an example based on a random array of words. You should be able to make it work with a small amount of modification.

 

<?php
$words = array(
'a',
'able',
'about',
'account',
'automatic',
'awake',
'baby',
'back',
'business',
'but',
'butter',
'button',
'by',
'cake',
'camera',
'curtain',
'curve',
'cushion',
'damage',
'danger',
'dark',
'daughter',
'driving',
'drop',
'dry',
'dust',
'ear',
'early',
'earth',
'east',
'edge',
'education',
'expansion',
'experience',
'expert',
'eye',
'face',
'fart',
'fall',
'full',
'future',
'garden',
'general',
'gun',
'hair',
'harmony',
'hat',
'hate',
'humour',
'ice',
'idea',
'iron',
'island',
'jelly'
);
$first = '';
foreach( $words as $v ) {
if(strtoupper($v[0]) !== $first ) {
	$first = strtoupper($v[0]);
	echo "<br>$first<br>";
}
echo "$v<br>";
}

why doesnt this work?

 

	$query = exec_mysql_query("SELECT *,substring(en,1,1) as term FROM translations WHERE substring(en,1,1) RLIKE '[$letter]' ORDER by en asc");
	$enterm = array();
	$esterm = array();
	$alt = array();

	while ($row = mysql_fetch_assoc($query)) {
	$term = $row['term'];
	$enterm[] = trim($row['en']);
	$esterm[] = trim($row['es']);
	$altterm[] = trim($row['alt']);
	$first = '';

	}
	foreach( $enterm as $en && $esterm as $es && $altterm as $alt) {
		if(strtoupper($en[0]) !== $first ) {
		$first = strtoupper($en[0]);
		echo "<br><b>$first</b><br>";
		}
	echo "$en - $es - $alt<br>";
	}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.