Answer the question
In order to leave comments, you need to log in
How to split a tree into pages (PHP+MySQL)?
I have a table with values:
term_ID | term_parent | term_title |
---|---|---|
one | 0 | Uncategorized |
2 | one | News |
3 | 2 | Sport |
4 | 3 | tennis |
5 | 0 | Articles |
//Выбираем данные из БД
$result=mysql_query("SELECT * FROM terms");
//Если в базе данных есть записи, формируем массив
if (mysql_num_rows($result) > 0){
$cats = array();
//В цикле формируем массив разделов, ключом будет id родительской категории, а также массив разделов, ключом будет id категории
while($cat = mysql_fetch_assoc($result)){
$cats_ID[$cat['term_ID']][] = $cat;
$cats[$cat['term_parent']][$cat['term_ID']] = $cat;
}
}
Array
(
[0] => Array
(
[0] => Array
(
[term_ID] => 1
[term_parent] => 0
[term_title] => Без рубрики
)
[1] => Array
(
[term_ID] => 5
[term_parent] => 0
[term_title] => Статьи
)
)
[1] => Array
(
[0] => Array
(
[term_ID] => 2
[term_parent] => 1
[term_title] => Новости
)
)
[2] => Array
(
[0] => Array
(
[term_ID] => 3
[term_parent] => 2
[term_title] => Спорт
)
)
[3] => Array
(
[0] => Array
(
[term_ID] => 4
[term_parent] => 3
[term_title] => Тенис
)
)
)
echo build_tree($cats,0);
function build_tree($cats,$parent_id,$only_parent = false){
if(is_array($cats) and isset($cats[$term_parent])){
$tree = '<ul>';
if($only_parent==false){
foreach($cats[$parent_id] as $cat){
$tree .= '<li>'.$cat['term_title'].' #'.$cat['term_ID'];
$tree .= build_tree($cats,$cat['term_ID']);
$tree .= '</li>';
}
}elseif(is_numeric($only_parent)){
$cat = $cats[$parent_id][$only_parent];
$tree .= '<li>'.$cat['term_title'].' #'.$cat['term_ID'];
$tree .= build_tree($cats,$cat['term_ID']);
$tree .= '</li>';
}
$tree .= '</ul>';
}
else return null;
return $tree;
}
Answer the question
In order to leave comments, you need to log in
Use nested set. You will be selecting the entire tree with one simple select that you can apply limit to.
www.getinfo.ru/article610.html
Assemble the tree completely, then cut N elements from the beginning, taking into account sub elements.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question