I do not post the final solution. But I hope it would give you an idea...
The table `names` should contain the field `category_id` - id of the category to which it belongs.
You simply names like this:
Code:
SELECT n.name
, c.category_name
, c.id
FROM names AS n
INNER
JOIN categories AS c
ON c.id=n.category_id
ORDER
BY c.id
, n.name
Here I assumed that category_id is always set to some category id and could not be null.
Then you pass the resultset in a loop and show the names for each category.
You could even do most of the work right in the SQL by using GROUP_CONCAT() ... (provided the DB is MySQL I mean)