Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-generate/loop a specific unordered list in PHP

Tags:

html

php

I want to make something like this:

  • A1
    • B1
      • C1
        • D1
        • D2
        • D3
      • C2
      • C3
    • B2
      • C4
        • D10
        • D11
        • D12
      • C5
      • C6
    • B3
      • C7
      • C8
      • C9
        • D25
        • D26
        • D27

So it's always groups of three, with every level ascending by a letter. First level is A, second B, C, D, E and so forth. The numbers are also listed in ascending order. Level A can only reach 1, B has 3, C has 9, D has 27, and so forth.

This is really easy to generate manually, converting the letters to their ASCII equivalent, adding one and converting them to character equivalent again. Problem is, I have to loop it till S, for instance, and my mind is getting messier and messier trying to put loops within loops.

What I got (toLetter and toNumber literally does what they do):

  echo "<ul><li>";
    echo "A1";
     echo "<ul><li>";
      $b = toNumber(A);
      $b++;
      $b = toLetter($b);
      $bnum = 1 - 1;
      $bnum = $bnum * 3;
      $bnum++;

      echo $b;
      echo $bnum."</li>";
      $bnum++;
      echo "<li>".$b;
      echo $bnum."</li>";
      $bnum++;
      echo "<li>".$b;
      echo $bnum."</li>";

Making this:

  • A1
    • B1
    • B2
    • B3

I really can't figure out how to just loop everything so it can reach till Z.

like image 460
Another Noob Avatar asked Oct 05 '22 00:10

Another Noob


2 Answers

A pretty simple version which only goes up to the 'C' level; increase as necessary.

<?php

function outputListItems($char) {
    static $index = array('A' => 1);

    if (!isset($index[$char])) {
        $index[$char] = 1;
    }

    for ($i = 0; $i < 3; $i++) {
        echo '<li>';
        echo $char;
        echo $index[$char]++;

        if ($char < 'C') {
            echo '<ul>';
            $nextChar = $char;
            outputListItems(++$nextChar);
            echo '</ul>';
        }

        echo '</li>';
    }
}

?>

<ul>
    <li>
        A1
        <ul><?php outputListItems('B'); ?></ul>
    </li>
</ul>

A is treated as special chase, since it only has one entry.

like image 85
deceze Avatar answered Oct 13 '22 11:10

deceze


in PHP, you can use ++ on a string, so you don't need to Letter/toNumber And to support unlimited nesting, you need a recursion (or at least it will be easier for you)

like image 40
Maxim Krizhanovsky Avatar answered Oct 13 '22 10:10

Maxim Krizhanovsky