tags:

views:

51

answers:

1

I asked a similar question earlier but I'll ask it again in a different way because I re-worked the code a little.

I was wondering how can I indent categories and endless sub categories that I have in a select drop down menu using PHP & CSS?

Here is my PHP code to display the select drop down.

echo '<select name="parent_id">
      <option value="0">None</option>';

function make_list ($parent) {

    global $option;

    foreach ($parent as $id => $cat) {

        echo '<option value="' . $cat['id'] . '">' . $cat['category'] . '</option>';

        if (isset($option[$id])) { 

            make_list($option[$id]);

        }                       
    }       
}

$mysqli = mysqli_connect("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT * FROM categories ORDER BY parent_id, category ASC");

if (!$dbc) {
    print mysqli_error();
} 

$option = array();

while (list($id, $parent_id, $category) = mysqli_fetch_array($dbc, MYSQLI_NUM)) {

    $option[$parent_id][$id] =  array('category' => $category, 'id' => $id, 'parent_id' => $parent_id);

}

make_list($option[0]);

echo '</select>';

Here is the output.

   1. Apple
   2. Arts & Entertainment
         1. Amusement
         2. Art
         3. Artists
               1. A
                     1. a1
                     2. a2
               2. B
               3. C
               4. D
   3. Automotive
   4. Network
   5. Server
   6. Web Design
         1. CSS
         2. HTML

The numbers are just there to see the categories and sub categories easier.

+1  A: 

I see you already have the recursion thing down -- try passing a "depth" parameter in your make_list function -- when you first call it, you'd set $depth to zero. Then, when you call it recursively, you'd say makelist($option[$id], $depth+1);

knowing what level of recursion you are on, you could easily construct a string of whitespace. Like:

$whitespace = str_repeat('&nbsp;', $depth);

for more indentation, try str_repeat('&nbsp;', $depth * 2); or similar

then just prepend your option with the whitespace.

Carson Myers
To elaborate on this append   instead of " " as having the spaces before an option tag will get trimmed. See http://jsfiddle.net/AxLUP/
Robert
@Carson Myers forgive me for my ignorance I'm kind of new to PHP where do I put the `for` code at in my code?
mudFLAP
you can use `$str = str_repeat(' ', INT)` but seriously, this is the third time he's opened this exact question...
Michael Robinson
@Michael didn't know about that function, I haven't used php in a while. And @mudFLAP use the `str_repeat` function, you're building a string of whitespace (the indent) to put in the option tag, so you'd use it before you `echo`ed the HTML.
Carson Myers