Elenco a discesa nidificato
Domanda
Sto costruendo un modulo con php / mysql. Ho una tabella con un elenco di posizioni e sublocazioni. Ogni sublocazione ha una posizione padre. Una colonna "parentid" fa riferimento a un altro locationid nella stessa tabella. Ora voglio caricare questi valori in un menu a discesa nel modo seguente:
--Location 1
----Sublocation 1
----Sublocation 2
----Sublocation 3
--Location 2
----Sublocation 4
----Sublocation 5
ecc. ecc.
Qualcuno ha una soluzione elegante per farlo?
Soluzione
NOTA: questo è solo psuedo-codice .. Non ho provato a eseguirlo, anche se dovresti essere in grado di adattare i concetti a ciò di cui hai bisogno.
$parentsql = "SELECT parentid, parentname FROM table";
$result = mysql_query($parentsql);
print "<select>";
while($row = mysql_fetch_assoc($result)){
$childsql = "SELECT childID, childName from table where parentid=".$row["parentID"];
$result2 = mysql_query($childsql);
print "<optgroup label=\".$row["parentname"]."\">";
while($row2 = mysql_fetch_assoc($result)){
print "<option value=\"".$row["childID"]."\">".$row["childName"]."</option>\n";
}
print "</optgroup>";
}
print "</select>";
Con in mente le valide critiche di BaileyP, ecco come farlo SENZA il sovraccarico di chiamare più query in ogni ciclo:
$sql = "SELECT childId, childName, parentId, parentName FROM child LEFT JOIN parent ON child.parentId = parent.parentId ORDER BY parentID, childName";
$result = mysql_query($sql);
$currentParent = "";
print "<select>";
while($row = mysql_fetch_assoc($result)){
if($currentParent != $row["parentID"]){
if($currentParent != ""){
print "</optgroup>";
}
print "<optgroup label=\".$row["parentName"]."\">";
$currentParent = $row["parentName"];
}
print "<option value=\"".$row["childID"]."\">".$row["childName"]."</option>\n";
}
print "</optgroup>"
print "</select>";
Altri suggerimenti
Stai cercando qualcosa come il OPTGROUP ?
optgroup è sicuramente la strada da percorrere. In realtà è quello che serve,
Ad esempio utilizzo, visualizza la fonte di http://www.grandhall.eu/tips/submit / - il selettore sotto " Grandhall Grill usato " ;.
Puoi usare il rientro spaziale / trattino nell'HTML attuale. Avrai bisogno di un ciclo ricusrivo per costruirlo però. Qualcosa del tipo:
<?php
$data = array(
'Location 1' => array(
'Sublocation1',
'Sublocation2',
'Sublocation3' => array(
'SubSublocation1',
),
'Location2'
);
$output = '<select name="location">' . PHP_EOL;
function build_items($input, $output)
{
if(is_array($input))
{
$output .= '<optgroup>' . $key . '</optgroup>' . PHP_EOL;
foreach($input as $key => $value)
{
$output = build_items($value, $output);
}
}
else
{
$output .= '<option>' . $value . '</option>' . PHP_EOL;
}
return $output;
}
$output = build_items($data, $output);
$output .= '</select>' . PHP_EOL;
?>
O qualcosa di simile;)
Idealmente, selezioneresti tutti questi dati nell'ordine corretto direttamente dal database, quindi esegui il ciclo su quello per l'output. Ecco la mia opinione su ciò che stai chiedendo
<?php
/*
Assuming data that looks like this
locations
+----+-----------+-------+
| id | parent_id | descr |
+----+-----------+-------+
| 1 | null | Foo |
| 2 | null | Bar |
| 3 | 1 | Doe |
| 4 | 2 | Rae |
| 5 | 1 | Mi |
| 6 | 2 | Fa |
+----+-----------+-------+
*/
$result = mysql_query( "SELECT id, parent_id, descr FROM locations order by coalesce(id, parent_id), descr" );
echo "<select>";
while ( $row = mysql_fetch_object( $result ) )
{
$optionName = htmlspecialchars( ( is_null( $row->parent_id ) ) ? "--{$row->descr}" : "----{$row->desc}r", ENT_COMPAT, 'UTF-8' );
echo "<option value=\"{$row->id}\">$optionName</option>";
}
echo "</select>";
Se non ti piace l'uso della funzione coalesce ()
, puoi aggiungere un " display_order " colonna di questa tabella che è possibile impostare manualmente, quindi utilizzare per ORDER BY
.