The method for reading tree data the method for reading tree data is generally used to read or read data from arrays layer by layer recursively when the data is organized by the "adjacent list algorithm, then use recursive or non-recursive methods to process the data again. here we will introduce a method to generate a "tree" array while reading, hoping to use mysql_connect (); to read the tree data.
How to Read tree data
Generally, recursive layer-by-layer reading is required when reading data organized by using the "adjacent list algorithm ".
Or read the data to the array, and then use recursive or non-recursive methods for processing.
This section describes how to generate a "tree" array while reading it.
Mysql_connect ();
// Test data
$ SQL = <SQL
Select * from (
Select '1' as id, '0' as pid, 'food' as title
Union all select '2', '1', 'fruit'
Union all select '3', '2', 'Red'
Union all select '4', '3', 'cherry'
Union all select '5', '2', 'yellow'
Union all select '6', '5', 'bana'
Union all select '7', '1', 'meat'
Union all select '8', '7', 'Beef'
Union all select '9', '7', 'pork'
) T
Order by pid, id
SQL;
$ Rs = mysql_query ($ SQL );
$ Res = array (); // result array
$ Ind = array (); // index array
While ($ row = mysql_fetch_assoc ($ rs )){
List ($ id, $ pid) = array_values ($ row );
$ Ind [$ id] = $ row;
If (isset ($ ind [$ pid]) $ ind [$ pid] ['child '] [$ id] = & $ ind [$ id]; // construct an index
If ($ pid = 0) $ res [$ id] = & $ ind [$ id]; // switch to the stub node group
}
Echo'
'& Nbsp ;. & nbsp; print_r ($ res, & nbsp; 1); <br/> </pre> Array <br/> (<br/> & nbsp; & nbsp; [1] & nbsp ;=>& nbsp; Array <br/> & nbsp; & nbsp; (<br/> & nbsp; & nbsp; [id] & nbsp ;=>& nbsp; 1 <br/> & nbsp; & nbsp; [pid] & nbsp ;=>& nbsp; 0 <br/> & nbsp; & nbsp; [title] & nbsp; => & nbsp; Food <br/> & nbsp; & nbsp; [child] & nbsp ;=>& nbsp; Array <br/> & nbsp; & nbsp; (<br/> & nbsp; & nbsp; & nbsp; [2] & nbsp ;=>& nbsp; Array <br/> & nbsp; & nbsp; & nbsp; (<br/> & nbsp; & nbsp; & nbsp; [id] & nbsp ;=>& nbsp; 2 <br/> & nbsp; & nbsp; & nbsp; [pid] & nbsp ;=>& nbsp; 1 <br/> & nbsp; & nbsp; & nbsp; & nbsp; [title] & nbsp ;=>& nbsp; Fruit <br/> & nbsp; & nbsp; & nbsp; [child] & nbsp ;=>& nbsp; array <br/> & nbsp; & nbsp; & nbsp; (<br/> & nbsp; & nbsp; & nbsp; & nbsp; [3] & nbsp ;=>& nbsp; Array <br/> & nbsp; & nbsp; & nbsp; & nbsp ;(