How to generate dynamic selectbox with optgroup

前端 未结 2 586
野趣味
野趣味 2021-01-29 08:22

Hi I am having this mysql table.

CREATE TABLE IF NOT EXISTS `selling_counties` (
  `county_id` int(11) NOT NULL auto_increment,
  `country` varchar(20) collate u         


        
相关标签:
2条回答
  • 2021-01-29 09:17

    You need to select the values from your table

    $mysqli = new mysqli($host, $user, $passwd, $database);
    $result = $mysqli->query('select county_id, country, county_name from selling_counties');
    $countries = array();
    while ($row = $result->fetch_assoc()) {
        $country = $row['country'];
        if (!array_key_exists($country, $countries))
            $countries[$country] = array();
    
        $countries[$country][] = array($row['county_id'], $row['county']);
    }
    

    and put these in your html select.

    Update to add county_id in <option>:

    <option value="<?php echo htmlentities($county[0]); ?>"><?php echo htmlentities($county[1]); ?></option>
    
    0 讨论(0)
  • 2021-01-29 09:19

    Create a new array like this, with countries as the keys, and the array of counties as each value. Assuming $rows is the array of raw table rows.

    <?php
    
    $countries = array();
    
    foreach($rows as $row)
    {
        if(isset($countries[$row['country']])) // <-- edit, was missing a ]
        {
            $contries[$row['country']][] = $row['county_name'];
        }
        else
        {
            $countries[$row['country']] = array($row['county_name']);
        }
    }
    
    ?>
    
    <select name ="county">
        <?php foreach($countries as $country => $counties): ?>
    
            <optgroup label="<?php echo htmlentities($country); ?>">
    
                <?php foreach($counties as $county): ?>
    
                    <option><?php echo htmlentities($county); ?></option>
    
                <?php endforeach; ?>
    
            </optgroup>
    
        <?php endforeach; ?>
    </select>
    
    0 讨论(0)
提交回复
热议问题