Pregunta

Estoy creando un formulario con php / mysql. Tengo una tabla con una lista de ubicaciones y sublocaciones. Cada sububicación tiene una ubicación principal. Una columna " parentid " hace referencia a otro locationid en la misma tabla. Ahora quiero cargar estos valores en un menú desplegable de la siguiente manera:

--Location 1
----Sublocation 1
----Sublocation 2
----Sublocation 3
--Location 2
----Sublocation 4
----Sublocation 5

etc. etc.

¿Alguien tiene una solución elegante para hacer esto?

¿Fue útil?

Solución

NOTA: Esto es solo un código psuedo. No intenté ejecutarlo, aunque deberías poder ajustar los conceptos a lo que necesitas.

$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 la crítica válida de BaileyP en mente, aquí se explica cómo hacerlo SIN la sobrecarga de llamar a múltiples consultas en cada bucle:

$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>";

Otros consejos

¿Está buscando algo como la etiqueta OPTGROUP ?

optgroup es definitivamente el camino a seguir. En realidad es para lo que es,

Por ejemplo, uso, vea la fuente de http://www.grandhall.eu/tips/submit / : el selector debajo de " Grandhall Grill Used " ;.

Puede usar una sangría de espacio / guión en el HTML real. Aunque necesitarás un bucle recusrive para construirlo. Algo como:

<?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 algo similar;)

Lo ideal sería que seleccionaras todos estos datos en el orden correcto desde la base de datos, y luego pasas por encima para obtener resultados. Aquí está mi opinión sobre lo que estás pidiendo

<?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>";

Si no le gusta el uso de la función coalesce () , puede agregar un " display_order " columna a esta tabla que puede configurar manualmente, y luego utilizar para el ORDER BY .

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top