After thinking for a bit, I realised that your solution would only allow 1 person to have 1 friend. To allow multiple friends you should use a lookup table in addition to the people table. Here's a bit of code I knocked together, you can play with and see how it works 🙂
# MySQL dump
CREATE TABLE `lookup` (
`id` int(11) default NULL,
`id_friend` int(11) default NULL
) TYPE=MyISAM;
INSERT INTO lookup VALUES("1","2");
INSERT INTO lookup VALUES("1","3");
INSERT INTO lookup VALUES("2","5");
INSERT INTO lookup VALUES("2","4");
INSERT INTO lookup VALUES("3","6");
CREATE TABLE `people` (
`id` int(11) unsigned NOT NULL auto_increment,
`name` varchar(25) default NULL,
`rank` varchar(25) default NULL,
PRIMARY KEY (`id`)
) TYPE=MyISAM;
INSERT INTO people VALUES("1","Jim","Commander");
INSERT INTO people VALUES("2","John","Captain");
INSERT INTO people VALUES("3","Jane","Captain");
INSERT INTO people VALUES("4","Joe","Grunt");
INSERT INTO people VALUES("5","Jack","Grunt");
INSERT INTO people VALUES("6","Jackie","Grunt");
$indent = 0;
function getFriendList($id)
{
global $indent;
$res = mysql_query("
SELECT t1.id, t1.name, t1.rank FROM people AS t1
INNER JOIN lookup as t2
ON t2.id = '$id'
WHERE t2.id_friend = t1.id
ORDER BY t1.id
");
while($friends = mysql_fetch_assoc($res))
{
// Do some display layup using $indent
echo str_repeat(" ", $indent).$friends['rank']." ".$friends['name']."<br>";
++$indent; // Move one level deeper
getFriendList($friends['id']); // Recurse
--$indent; // Go back up
}
}
echo "General Jim<br>"; // Gotta do this as we're not looking up the highest member's details
++$indent;
getFriendList(1);
Hope this is the kinda thing you were looking for. Now gotta run, late for work 😃