我有一个SQL表,其中包含一个ID和一个分配给同一个表的外键。我正在使用它来通过PHP管理网页中的(子)导航点。
(page_id 6当然应该为page_fs设为5,对不起该错字
如您所见,如果page_fs等于零,则它是顶级,如果不是,则它是具有相同ID的页面的子导航。
使用PHP获取此类列表的最有效方法是什么:
第1页
- 第1.1页
- 第1.2页
----页1.2.1
第2页
- 第2.1页
Page 3
它应该支持无限量的图层。
感谢您的帮助
答案 0 :(得分:1)
我想最有效的方法是将position
和level
存储在数据库中。但是,如果不能或不想这样做,可以使用以下方法在数组结构中表示导航:
<?php
/* SQL:
SELECT * FROM `navigation` ORDER BY `page_fs` DESC, `page_id
result in: */
$sql_result = [
['page_id' => 6, 'page_fs' => 5, 'title' => 'Page 2.1' ],
['page_id' => 4, 'page_fs' => 3, 'title' => 'Page 1.2.1' ],
['page_id' => 2, 'page_fs' => 1, 'title' => 'Page 1.1' ],
['page_id' => 3, 'page_fs' => 1, 'title' => 'Page 1.2' ],
['page_id' => 1, 'page_fs' => 0, 'title' => 'Page 1' ],
['page_id' => 5, 'page_fs' => 0, 'title' => 'Page 2' ],
['page_id' => 7, 'page_fs' => 0, 'title' => 'Page 3' ]
];
function buildNavigation( $pages ) {
$navigation = [];
/* this loop assign each page to its id as an index
* Initializing ['children'] is optional. You'll' either
* have for every element or only for those which
* actually have children .*/
foreach($pages as $key => $page) {
$navigation[ $page['page_id'] ] = $page;
$navigation[ $page['page_id'] ]['children'] = [];
}
/* Bring every element as a child to its parent and unset its
* top level representation. */
foreach($pages as $key => $page) {
if( $page['page_fs'] > 0 ) {
$navigation[ $page['page_fs'] ][ 'children' ][] = $navigation[$page['page_id']];
unset($navigation[$page['page_id']]);
}
}
return $navigation;
}
echo "<pre>";
print_r( buildNavigation($sql_result) );
echo "<pre>";
?>
使用该结构,简单的递归函数可以将此结构传输到所需的html输出中。