Skip to content

Instantly share code, notes, and snippets.

@w-mazed
Created January 4, 2021 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save w-mazed/b4c8fcc5cc0f9cfd189c183fd1938f8a to your computer and use it in GitHub Desktop.
Save w-mazed/b4c8fcc5cc0f9cfd189c183fd1938f8a to your computer and use it in GitHub Desktop.
Create Category tree with PHP and MySQL
<?php
/**
* Creating category Tree using recursion.
*======================================================*/
function fetchCategoryTree($parent = 0, $spacing = '', $user_tree_array = array())
{
$sql = "SELECT `cid`, `name`, `parent` FROM `category` WHERE 1 AND `parent` = $parent ORDER BY cid ASC";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_object($query)) {
$user_tree_array[] = array("id" => $row->cid, "name" => $spacing . $row->name);
$user_tree_array = fetchCategoryTree($row->cid, $spacing . '&nbsp;&nbsp;', $user_tree_array);
}
}
return $user_tree_array;
}
/**
* Display the category tree in a dropdown list.
*======================================================*/
$categoryList = fetchCategoryTree(); ?>
<select>
<?php foreach ($categoryList as $cl): ?>
<option value="<?php echo $cl["id"] ?>"><?php echo $cl["name"]; ?></option>
<?php endforeach; ?>
</select>
<?php
/**
* Displaying Category tree in list format.
*======================================================*/
function fetchCategoryTreeList($parent = 0, $user_tree_array = array())
{
$sql = "SELECT `cid`, `name`, `parent` FROM `category` WHERE 1 AND `parent` = $parent ORDER BY cid ASC";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
$user_tree_array[] = "<ul>";
while ($row = mysql_fetch_object($query)) {
$user_tree_array[] = "<li>" . $row->name . "</li>";
$user_tree_array = fetchCategoryTreeList($row->cid, $user_tree_array);
}
$user_tree_array[] = "</ul>";
}
return $user_tree_array;
} ?>
<ul>
<?php
$res = fetchCategoryTreeList();
foreach ($res as $r) {
echo $r;
} ?>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment