简体   繁体   中英

How to put categories and subcategories on selectbox with optgroup with just one query with PHP?

I would like to know how is possible with one just query make the selectbox with categories and subcategories with optgroup.

Table category:

cat_id  int(10) unsigned Auto Increment  
cat_catid   int(10) unsigned NULL    
cat_name    varchar(100)

Content:

| cat_id | cat_catid | cat_name      |
+--------+-----------+----------------
|      1 |      NULL | Category - A  |
|      2 |         1 | 1             |
|      3 |         1 | 2             |
|      4 |      NULL | Category - B  |
|      5 |         4 | 1             |
|      6 |         4 | 2             |
|      7 |         4 | 3             |

With one query and PHP make it into:

<select>
<optgroup label="Area - A">
    <option>1</option>
    <option>2</option>
</optgroup>
<optgroup label="Area - B">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</optgroup>
</select>

You're going to need some post processing in PHP of your query. I prefer restructuring the rows to a multidimensional array:

$rows = query("SELECT * FROM table ORDER BY cat_catid"); // (Just make sure NULL's are first)

$cats = [];
foreach ( $row as $row ) {
    // Do we have a root category?
    if ( $row['cat_catid'] === null ) {
        // Start a new array, and no children
        $cats[ $row['cat_id'] ] = [
            'name' => $row['cat_name'],
            'children' => []
        ];
    } else {
        // Add this category name to the parent category ID.
        $cats[ $row['cat_catid'] ]['children'][] = $row['cat_name'];
    }
}

echo '<select>';

foreach ( $cats as $cat ) {
    echo '<optgroup label="', $cat['name'], '">';
    foreach ( $cat['children'] as $child ) {
        echo '<option>', $child, '</option>';
    }
    echo '</optgroup>';
}

echo '</select>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM