PHP嵌套导航
我正在建立一个数据库驱动的导航,我需要一些帮助来建立我的数据结构。我对递归不是很有经验,但这很可能就是这条路。数据库表有一个id列、一个parent_id列和一个label列。调用该方法的结果为我提供了数据结构。我的数据结构应产生以下结果:PHP嵌套导航,php,recursion,navigation,Php,Recursion,Navigation,我正在建立一个数据库驱动的导航,我需要一些帮助来建立我的数据结构。我对递归不是很有经验,但这很可能就是这条路。数据库表有一个id列、一个parent_id列和一个label列。调用该方法的结果为我提供了数据结构。我的数据结构应产生以下结果: 父\u id为0的记录假定为根元素 如果存在一个子元素,则每个根元素都包含一个子元素数组,该子元素包含一个包含与根元素id相等的父元素id的元素数组 子元素可能包含一个子元素数组,该数组包含与直接子元素相等的父元素ID(这将是递归点) 当存在一个包含非0的
- 父\u id为0的记录假定为根元素
- 如果存在一个子元素,则每个根元素都包含一个子元素数组,该子元素包含一个包含与根元素id相等的父元素id的元素数组
- 子元素可能包含一个子元素数组,该数组包含与直接子元素相等的父元素ID(这将是递归点)
- 当存在一个包含非0的父\u id的记录时,它将被添加到子元素的数组中
$data = array(
'home' => array(
'id' => 1,
'parent_id' => 0,
'label' => 'Test',
'children' => array(
'immediatechild' => array(
'id' => 2,
'parent_id' => 1,
'label' => 'Test1',
'children' => array(
'grandchild' => array(
'id' => 3,
'parent_id' => 2,
'label' => 'Test12',
))
))
)
))
这是我几分钟后想到的。它是不正确的,但它是我想要使用的,我需要一些帮助来修复它
<?php
// should i pass records and parent_id? anything else?
function buildNav($data,$parent_id=0)
{
$finalData = array();
// if is array than loop
if(is_array($data)){
foreach($data as $record){
// not sure how/what to check here
if(isset($record['parent_id']) && ($record['parent_id'] !== $parent_id){
// what should i pass into the recursive call?
$finalData['children'][$record['label'][] = buildNav($record,$record['parent_id']);
}
}
} else {
$finalData[] = array(
'id' => $data['id'],
'parent_id' => $parent_id,
'label' => $data['label'],
)
}
return $finalData
}
最简单的解决方案(假设您已将数据存储在关系表示中,并使用父id作为FK来指示层次结构)是强制执行它:
$start=array(
array('parent_id'=>0, 'title'=>'Some root level node', 'id'=>100),
array('parent_id'=>0, 'title'=>'Other root level node', 'id'=>193),
array('parent_id'=>100, 'title'=>'a child node', 'id'=>83),
....
);
// NB this method will work better if you sort the list by parent id
$tree=get_children($start, 0);
function get_children(&$arr, $parent)
{
static $out_index;
$i=0;
$out=array();
foreach($arr as $k=>$node) {
if ($node['parent_id']==$parent) {
++$i;
$out[$out_index+$i]=$node;
if (count($arr)>1) {
$out[$out_index+$i]['children']=get_children($arr, $node['id']);
}
unset($arr[$k]);
}
$out_index+=$i;
if ($i) {
return $out;
} else {
return false;
}
}
但是,更好的解决方案是对数据库中的数据使用。作为临时解决方案,您可能希望序列化树数组并将其缓存在文件中,而不是每次都对其进行解析。如果您使用MySQL作为数据存储,那么您可能会喜欢这样:对于thingsFIxed的DB端。我正在寻找php代码来构建导航数据结构。到目前为止,您尝试了什么?我们是来帮忙的,但不只是根据要求写代码。我希望我能说我有进展,但我没有。我真的不知道如何解决这个问题(我被递归弄糊涂了)。此外,我真的不知道如何使用PHP编程递归。“我不知道如何使用PHP编程递归”,就像在大多数其他语言中一样,通过从函数本身调用函数。感谢您的回复。我宁愿用我的方法。你能看一下并告诉我它是否可行吗?可能需要修理一下。