tags:

views:

53

answers:

3

hi i would like to create nested divs dynamically, preferably without javascript

so if you have n divs, div1 contains div2 which contains div3 which etc ...

how could I code that in php ?

Tom

+1  A: 

Here is a simple loop example using $n = 3. You can change $n to any number and it will nest div tags for you. I'm not entirely sure why you would want to do this, but here it is.

$openingTags = '';
$closingTags = '';

$n = 3;

for ($i = 0; $i < $n; ++$i) {
    $openingTags .= '<div id="div' . $i . '">';
    $closingTags .= '</div>';
}

echo $openingTags . 'Hello World' . $closingTags;
Sohnee
thx - aim is creating nested divs for yui nested tabview where number of tabs and corresponding nested divs depends on number of rows returned by a query. i ran your code and now am puzzling how to insert content into each div i.e div-1 (somecontent) div-2 (somecontent+) div-3 (somecontent++) /div-3 /div-2 /div-1
Tom
+2  A: 
function recursiveDiv($num)

  $html = '<div id="div'.$num.'">%s</div>';

  for($i = $num - 1; $i >= 1; $i--) {
    $html = '<div id="div'.$i.'">'.$html.'</div>';
  }
  return $html;
}

echo sprintf(recursiveDiv(5), 'Hello World');

Untested but should give you want you want.

Ben Rowe
A: 

This code should allow you to create the nested divs and also populate them with content. Replaced orginal code with below, this should work but its untested

<?php
$result = mysql_query("SELECT * FROM table");
$count = mysql_num_rows($result);
$html = '';
$end_html = '';
while($row = mysql_fetch_object($result)){
  $html .= '<div id="div'.$count.'">'.$row->textfield; # any database column
  $end_html .= '</div>';
  $count--;
}
echo $html . $end_html;
Luke
Thx one and all. I had a feeling that it ought to be simple. And it turned out not to be.
Tom
There may well be a more simple solution than mine, its just the first thing that came to my head, is there anything in particular that you dont understand? if you want dynamic content you could dynamically generate the array you parse to my function.
Luke
After reading your comment from @Sohnee's code I have modified the code to create an array from a query, hope this helps
Luke
Simplified as much as I can
Luke
hi Luke - thx for simpler to look at code. Dynamic nested tabview w yui ought to be do-able now. Tom
Tom
np hope it works
Luke
dropped yr code into a page to check: it works v well. question: removing the . from the = kills the recursive effect: can I ask you how the .= does its magic ?
Tom
$html .= 'luke' is the same as $html = $html . 'luke' so it concatenates rather than replaces.
Luke
Got it! Soooo the php whiles away adding as it were little snips of the same html together i.e <div3>content3 <div2>content2 <div1>content1 giving the required nesting etc thx again!
Tom