문제

PHP/MySQL로 양식을 작성하고 있습니다. 위치 및 하위 지역 목록이있는 테이블이 있습니다. 각 하위 위치에는 부모 위치가 있습니다. "parentid"열은 같은 테이블에 다른 locationID를 참조합니다. 이제이 값을 다음과 같은 방식으로 드롭 다운에로드하고 싶습니다.

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

기타 등

누구 든지이 작업을위한 우아한 솔루션을 얻었습니까?

도움이 되었습니까?

해결책

참고 : 이것은 단지 psuedo-code입니다. 나는 그것을 실행하려고 시도하지 않았지만, 당신은 필요한 것에 대한 개념을 조정할 수 있어야합니다.

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

Baileyp의 유효한 비판을 염두에두고 모든 루프에서 여러 쿼리를 호출하는 오버 헤드없이 수행하는 방법은 다음과 같습니다.

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

다른 팁

당신은 The와 같은 것을 찾고 있습니까? 옵트 그룹 꼬리표?

OptGroup은 확실히 갈 길입니다. 그것은 실제로 그것이 무엇인지,

예를 들어 사용법, 소스를 봅니다 http://www.grandhall.eu/tips/submit/ - "Grandhall Grill 사용"의 선택기.

실제 HTML에서 공간/대시 압입을 사용할 수 있습니다. 그래도 구축하려면 Recusrive 루프가 필요합니다. 같은 것 :

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

?>

또는 비슷한 것;)

이상적으로는이 모든 데이터를 데이터베이스에서 바로 적절한 순서로 선택한 다음 출력을 위해 루프를 반복합니다. 여기에 당신이 요구하는 것에 대한 내 생각이 있습니다

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

당신이 사용하는 것을 좋아하지 않는다면 coalesce() 함수, 수동으로 설정할 수있는이 테이블에 "display_order"열을 추가 한 다음 ORDER BY.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top