I would like to create nested divs dynamically, preferably without JavaScript.
So if you have n
number of DIVs, DIV1 contains DIV1 which contains DIV3 etc…
How would I code that in PHP?
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;
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.
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
$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;
While others are suggesting using mathematical solutions based on for
loops, you can do this a bit more explicitly—clearly setting classnames—by using an array like this:
// Set the DIVs array.
$divs_array = array();
$divs_array[] = 'DIV1';
$divs_array[] = 'DIV2';
$divs_array[] = 'DIV3';
Now with that array set, you can use implode
to take the content of those arrays and set them as DIV class values like this. Note the implode
logic might seem confusing, but look at what it creates and look at how the code is set and it makes more sense after a while:
// Set the DIVs.
$div_opening = $div_closing = '';
if (!empty($divs_array)) {
$div_opening = '<div class="' . implode($divs_array, '">' . "
" . '<div class="') . '">';
$div_closing = '</div><!-- .' . implode(array_reverse($divs_array), '-->' . "
" . '</div><!-- .') . ' -->';
}
And then you can set the content between the $div_opening
and $div_closing
values like this:
// Return the content wrapped in the DIVs.
echo $div_opening
. '<p>Hello world.</p>'
. $div_closing
;
The output would be something like this:
<div class="DIV1">
<div class="DIV2">
<div class="DIV3">
<p>Hello world.</p>
</div><!-- .DIV3 -->
</div><!-- .DIV2 -->
</div><!-- .DIV1 -->
Note my personal coding style is to—whenever possible—set comments after each DIV that clearly shows what that </div>
is actually closing. So that is what the comments like <!-- .DIV3 -->
refer to; feel free to adjust to fit your own coding needs and style.