Dynamically create nested divs in PHP

I would like to create nested divs dynamically, preferably without JavaScript.

So, if you have a nnumber of DIV, DIV1 contains DIV1, which contains DIV3, etc.

How do I encode this in PHP?

+3
source share
4 answers
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');

Unconfirmed, but should give you the desire you want.

+3
source

Here is a simple loop example using $ n = 3. You can change $ n to any number and it will set div tags for you. I'm not quite sure why you 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;
+2
source

divs . , ,

$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;
+1

for, , - :

// Set the DIVs array.
$divs_array = array();
$divs_array[] = 'DIV1';
$divs_array[] = 'DIV2';
$divs_array[] = 'DIV3';

implode, DIV, , , implode , , , , , :

// Set the DIVs.
$div_opening = $div_closing = '';
if (!empty($divs_array)) {
  $div_opening = '<div class="' . implode($divs_array, '">' . "\n" . '<div class="') . '">';
  $div_closing = '</div><!-- .' . implode(array_reverse($divs_array), '-->' . "\n" . '</div><!-- .') . ' -->';
}

$div_opening $div_closing :

// Return the content wrapped in the DIVs.
echo $div_opening
   . '<p>Hello world.</p>'
   . $div_closing
   ;

:

<div class="DIV1">
<div class="DIV2">
<div class="DIV3">
<p>Hello world.</p>
</div><!-- .DIV3 -->
</div><!-- .DIV2 -->
</div><!-- .DIV1 -->

, - - DIV, , </div> . <!-- .DIV3 -->; , .

0
source

Source: https://habr.com/ru/post/1751151/


All Articles