Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.