Created
January 4, 2021 08:42
-
-
Save w-mazed/b4c8fcc5cc0f9cfd189c183fd1938f8a to your computer and use it in GitHub Desktop.
Create Category tree with PHP and MySQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 . ' ', $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