Re: Recursively determine parent records?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



http://www.sitepoint.com/print/hierarchical-data-database
has a guide on how to do the same thing but in a single SQL query, without looping at all. It is very interesting reading and requires a slight restructuring of how the records are stored to pull off but with the wonderful result in being much faster to retrieve.


Chris Gregors wrote:
Here's a piece of some code I wrote that does what you want. You'll need
to change the WhoIsMyParent() function to match your database
abstraction and schema.

$array = BreadCrumbs($id);
print_r($array);
exit;

function BreadCrumbs($parent) {
	// construct an array of indexes that represents the path back
to the
	// root from my current location in the tree.
	$PathStack = array();
	array_push($PathStack,$parent);
	$MyParent = WhoIsMyParent($parent);
	while ($MyParent != 0) {			// 0 = top of
the tree
		$PathStack[] = $MyParent;
		$MyParent = WhoIsMyParent($MyParent);
	}
	$PathStack = array_reverse($PathStack);
	return $PathStack;
}

function WhoIsMyParent($id) {
	$row=FetchRow(QueryDb("select parent from sometable where
id=".$id));
	if ($row == NULL) return 0;
	return $row['parent'];
}

-----Original Message-----
From: Murray @ PlanetThoughtful [mailto:lists@xxxxxxxxxxxxxxxxxxxx]
Sent: Tuesday, October 05, 2004 11:58 PM
To: php-db@xxxxxxxxxxxxx
Subject:  Recursively determine parent records?




Hi All,



I have recordset that contains a hierarchical representation of records
where a record's [parentid] field contains the recid of the record
'above'
the current record.



A representation might look like this:



Recid, parentid, title



1, 0, Top level record

2, 0, Another top level record

3, 1, A record under the top level record

4, 3, Another level

5, 2, A record under the second top level record



If I have currently retrieved the record with recid of 4, I want to work
out
the 'chain' of records that lead back to the top level record it has
been
created under.



In this instance, that chain would look like:



4, 3, Another level

3, 1, A record under the top level record

1, 0, Top level record



I'm wondering if anyone can help me work out how to achieve this?



Many thanks in advance!



Much warmth,



Murray

 <http://www.planetthoughtful.org/> http://www.planetthoughtful.org

Building a thoughtful planet,

One quirky comment at a time.




-- PHP Database Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [PHP Users]     [Postgresql Discussion]     [Kernel Newbies]     [Postgresql]     [Yosemite News]

  Powered by Linux