Question

-EDIT- <li> would probably be better but the same question still applies.

So I have everything working as far as I can display the data and get the expected results. The display portion I have is coming from the article at http://www.sitepoint.com/hierarchical-data-database-2/

I have:

$right = array();
    $show = "";
    while ($row = mysql_fetch_array($title)) {          
        if (count($right)>0) {
            while (count($right)>0&&($right[count($right)-1]<$row['rgt'])) {
                array_pop($right);
            } 
        }

        $show .= str_repeat('->',count($right)).$row['title'].count($right)."<br>";  
        $right[] = $row['rgt'];
    }
    return $show;

It works as expected. What I want to do now is enclose them properly in divs. So I want it to look something like:

<div>
  Title
  <div>
    subtitle
      <div>
        subsubtitle
      </div>
    </div>
</div>
<div>
  Title2
  <div>
    subtitle2
      <div>
        subsubtitle2
      </div>
    </div>
</div>

So you can see the top Title div encloses all the subs of that div and so on. I am not sure how to go about this. I can see that what I want to do is once count($right) is again equal to the count of the div is when to close the div, but again, not sure how to go about it.

Était-ce utile?

La solution

One approach is to organize the data into a structure that you can more easily iterate:

$divs = array();
while ($row = mysql_fetch_array($title)) {          
    $divs[$row['left']] = array('type'=>'open', 'text'=>$row['title']);
    $divs[$row['rgt']]  = array('type'=>'close');
}

$divCount = count($divs);
for ($d=1; $d<$divCount; $d++) {
    if ($divs[$d]['type'] == 'open') {
        echo "<div>" . $divs[$d]['text'];
    } else {
        echo "</div>";
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top