How to dump an array in a multiple select

0

I have a form that has a multiple select that is loaded with data from a database. In this select, the user selects several "interests". In the process of saving the data, I keep the array in the database with this format:

["17","12","11","13","5"]

Now comes the moment when I have to recover what the user selected. As a frame as "selected" those items whose values are those that are stored in the database?

    
asked by MNibor 30.07.2017 в 01:41
source

2 answers

1
<select name="nombre" multiple>
<?php
$seleccionados = ["17","12","11","13","5"];
foreach($valores as $clave => $nombre) {
    // Verificas si la clave está en los seleccionados
    $sel = (in_array($clave, $seleccionados)) ? ' selected' : '';
    echo "<option value=\"$clave\"$sel>$nombre</option>";
}
?>
</select>
    
answered by 30.07.2017 / 02:23
source
0

If someone is interested, this works:

<select id="selectIntereses" class="ui fluid search dropdown" multiple name="intereses[]">
                    <option value="0"></option>
                    <?php
                        //Traigo el array de intereses
                        $valores = json_decode ($intereses, true);

                        $conexion = new Conexion();
                        $stmt = $conexion -> prepare("SELECT id, interes FROM intereses WHERE vigente=1 ORDER BY interes");
                        $stmt->execute();
                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                          foreach ($valores as $key => $value) {
                              if ($value == $row['id']) { ?>
                                 <option value = "<?php echo $row['id']?>" selected><?php echo utf8_encode($row['interes'])?></option>
                              <?php }else{ ?>
                                 <option value = "<?php echo $row['id']?>"><?php echo utf8_encode($row['interes'])?></option>
                              <?php }
                            }
                        }
                    ?>
                </select>
    
answered by 30.07.2017 в 17:53