Skip to content

Instantly share code, notes, and snippets.

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 rakeshkumar125/094817759e515e5f3dea3ff75d99ec50 to your computer and use it in GitHub Desktop.
Save rakeshkumar125/094817759e515e5f3dea3ff75d99ec50 to your computer and use it in GitHub Desktop.
Tree structure category menu with mysql minimum query using array
<?php
function treeMenu($parent, $data){
$childs = getChild($parent,$data);
$text = '';
if(count($childs)>0){
foreach ($childs as $child) {
$text .= '<li class="menucolor">'
.'<a href="' . htmlspecialchars($child['link']) . '">' . htmlspecialchars($child['title']) . '</a>'
. treeMenu($child['id'],$data) . '</li>';
}
}
if( $text == '' )
return '';
return '<ul id="red" class="treeview-red">' . $text . '</ul>';
}
function getChild($parent,$data){
$returnchild = array();
foreach($data as $d){
if($d['id_parent']==$parent){
$returnchild[] = $d;
}
}
return $returnchild;
}
$conn = new mysqli("localhost", "root", "", "test");
$result = $conn->query("SELECT id,id_parent,title,link FROM `menu`");
$completeData = array();
while($row = $result->fetch_assoc()){
$completeData[] = $row;
}
echo treeMenu(0,$completeData);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment