Multi-level Product Tree in PHP
June 5th, 2007
Let us say that you wish to have multi-level display in an unordered list, much like a tree. This could be products, categories, or whatever you wish. In this example, we are going to use products with tree-like associations, and display them in an unordered list.
First, the SQL table. In this example we will use a MySQL database table called mockProducts. Here is the structure for that.
-
CREATE TABLE `mockProducts` (
-
`id` int(11) NOT NULL AUTO_INCREMENT,
-
`parent` int(11) NOT NULL DEFAULT ‘0′,
-
`productName` varchar(50) DEFAULT NULL,
-
`price` decimal(10,0) DEFAULT NULL,
-
PRIMARY KEY (`id`)
-
) TYPE=MyISAM;
Here is some PHP code which will construct the tree-like unordered list.
-
-
//————————————————————————-
-
// Get a listing of all the first-level products. Their parent level is set
-
// to zero (0).
-
//————————————————————————-
-
$productsFirstLevel = mysql_query("SELECT id, productName, price FROM mockProducts WHERE parent=0 ORDER BY productName");
-
-
//——————————————————-
-
// Construct the HTML for the multi-level unordered list.
-
//——————————————————-
-
function constructTree($query, &$html)
-
{
-
{
-
<li>%s ($%s)</li>
-
", $row->productName, $row->price);
-
$nextQuery = mysql_query("SELECT id, productName, price FROM mockProducts WHERE parent=".$row->id." ORDER BY productName");
-
-
{
-
$html .= "
-
<ul>";
-
constructTree($nextQuery, $html);
-
$html .= "</ul>
-
";
-
}
-
}
-
}
-
-
$html = "
-
<ul>";
-
constructTree($productsFirstLevel, $html);
-
$html .= "</ul>
-
";
-
-
-
?>
Happy coding!