Php Generate Ul Li , Ul Li
Can't figure out how-to generate this menu using a while-loop. This is an example of my code:
Solution 2:
functionload()
{
global$conn;
$query = "SELECT * FROM sub_category WHERE main_category_id='1'";
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_assoc($result)){
$cat_id=$row['sub_category_id'];
echo'<li><a href="?id='.$row['sub_category_id'].'">'.$row['sub_category_name'].'</a>';
$query2 = "SELECT * FROM categories WHERE sub_category_id='$cat_id'";
$result2 = mysqli_query($conn,$query2);
echo'<ul class="sub">';
while($row2 = mysqli_fetch_assoc($result2))
{
echo'<li><a href="?id='.$row2['category_id'].'">'.$row2['category_name'].'</a></li>';
}
echo'</ul>';
echo'</li>';}
}
Solution 3:
in this example parent_id column used and ul-li list build with references- it makes only 1 sql query and use recoursion for rendering output, this code can be simply changed for your needs
<?php/**
* Module for displaying data from items table
*/classApp_Modules_TreeextendsApp_AbstractModule{
/**
* array for storing data
*
* @var array
*/private$tree = array();
/**
* html - output of current module
*
* @var string
*/private$output = '';
/**
* Retreives data from table items.
*
* @return void
*/privatefunction_getData()
{
$pdo = App_Registry::get('pdo');
$levels = array();
foreach ($pdo->query('SELECT * FROM items ORDER BY parent_id ASC',PDO::FETCH_OBJ) as$k=>$v){
// references$current = &$levels[ $v->id ] ;
$current['parent_id'] = $v->parent_id;
$current['name'] = $v->name;
if (0 == $v->parent_id){
$this->tree[ $v->id ] = &$current;
} else {
$levels[$v->parent_id ]['children'][$v->id] = &$current;
}
}
}
/*
*App_AbstractModule::preRender overriding
* @return void
*/protectedfunctionpreRender()
{
$this->_getData();
}
/**
* recursively build html output.
*
* @return string
*/privatefunction_render($arr)
{
$this->output.= '<ul>';
foreach ($arras$k=>$v)
{
$this->output.= '<li>'.$v['name'].'</li>';
if( !empty($v['children'])){
$this->_render($v['children']);
}
}
$this->output.= '</ul>';
return$this->output;
}
/*
*App_AbstractModule::render overriding
* @return string
*/protectedfunctionrender()
{
return$this->_render($this->tree);
}
}
Post a Comment for "Php Generate Ul Li , Ul Li"