对不起伙计们再次使用我的递归数组,它确实有效,但我不能正确地使用<ul>
,<li>
得到的“布局”是一个“正确的”树结构,所以你最终像这样:
我的功能看起来像这样 - 虽然功能正常,但“布局”并没有建议。
function recursive_array($results,$tbl) {
global $DBH;
$tbl = $tbl;
if (count($results)) {
foreach($results as $res) {
if( $res->ParentID == 0 ) {
echo '<ul class="recursive">';
echo '<li>';
echo $res->Name;
echo $res->Description;
echo $res->date_added;
echo '<ul>';
}
if( $res->ParentID != 0 ) {
echo '<li>';
echo $res->Name;
echo $res->Description;
echo $res->date_added;
echo '</li>';
}
$STH = $DBH->query("SELECT * FROM ".$tbl." WHERE ParentID = '".$res->ID."'");
$fquerycount = $STH->rowCount();
$STH->setFetchMode(PDO::FETCH_OBJ);
recursive_array($STH,$tbl);
if( $res->ParentID == 0 ) {
echo '</ul></li></ul>';
}
}
}
}
答案 0 :(得分:1)
我真的不喜欢递归SQL。我已经习惯了它,它有效,但总是让我感到震惊......是的......
相反如何:创建一个topicID(某种选择器,它将包含你最终想要输出的所有项目)并根据它选择,由parentID排序。
SELECT * FROM $tbl WHERE topicID = 1 ORDER BY parentID;
然后,你像这样组织:
$output = array();
$currentParent = -1;
while( $row = $stmt->fetch(PDO::FETCH_OBJ) )
{
if( $currentParent != $row->ParentID )
{
$currentParent = $row->ParentID;
$output[ $currentParent ] = array();
}
$output[ $currentParent ][] = $row;
}
function outputLists( array $current, array $output )
{
echo '<ul>';
foreach( $current as $res )
{
echo '<li>';
echo $res->Name;
echo $res->Description;
echo $res->date_added;
// if it is set, clearly we have a node to traverse
if( isset( $output[ $res->ID ] ) )
// seed the next call to the function with the new
// node value (found in output) and it will create
// the appropriate ul and li tags
outputLists( $output[ $res->ID ], $output );
echo '</li>';
}
echo '</ul>';
}
// start with the group with parentID = 0
outputLists( $output[ 0 ], $output );
因此,您没有使用递归SQL,而是从数据库中获得一个输出,在PHP中创建树状结构。