Recursive array correct method of display
Sorry guys back again with my recursive array which does work but I cannot get the "layout" right what I am after is a "proper" tree structure using <ul>
,<li>
so you end up like this:
- Item
- Child
- Child of child
- Etc...
- Child of child
- Child
My function looks like this - whilst the function works the "layout" does not suggestions please.
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);
开发者_JS百科 if( $res->ParentID == 0 ) {
echo '</ul></li></ul>';
}
}
}
}
I am really not a fan of recursive SQL. I've used it, it works, but it always struck me as... yeck...
How about this instead: create a topicID (some sort of selector which will include all of the items which you would eventually like to have output) and select based on that, ordered by parentID.
SELECT * FROM $tbl WHERE topicID = 1 ORDER BY parentID;
Then, you organize like this:
$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 );
So, instead of having recursive SQL, you have one output from the database creating a tree-like structure in PHP.
精彩评论