填充OPTGROUP和嵌套的OPTION值

时间:2016-03-16 12:10:24

标签: php jquery json

我有一个PHP文件,它将ID作为输入并输出数组。

这个想法是第一个SQL将生成一个类别值列表,用作OPTGROUP的标签。

第二个SQL查找属于父类别的帖子,并将它们添加到数组中。

PHP

 $sql = "SELECT cats.fld_label
              , cats.fld_id
           FROM tbl_b_cats cats
          WHERE cats.fld_parent = ?
       ORDER BY cats.fld_label";

$stmt = $conn->stmt_init();
if (!$stmt->prepare($sql)) { throw new Exception("Error preparing statement: $stmt->error, SQL query: $sql"); }
if (!$stmt->bind_param('s', $_GET['cat_parent'])) { throw new Exception("Error binding parameter: $stmt->error"); }
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 0) {
    header('HTTP/1.0 404 Not Found');
    exit;
} else {
    $AjaxOptGpLabel = array();
    $stmt->bind_result($fld_label, $fld_id);
    while ($stmt->fetch()) {
        $query = "SELECT fld_id fld_id2, fld_title fld_title2 FROM tbl_c_posts WHERE fld_catid = ? ORDER BY fld_title";
        $stmt2 = $conn->stmt_init();
        if (!$stmt2->prepare($query)) { throw new Exception("Error preparing statement: $stmt2->error, SQL query: $query");}
        if (!$stmt2->bind_param('s', $fld_id)) {throw new Exception("Error binding parameter: $stmt2->error");}
        $stmt2->execute();
        $stmt2->store_result();
        if ($stmt2->num_rows > 0){
            $AjaxOptGpPosts = array();
            $stmt2->bind_result($fld_id2, $fld_title2);
            while ($stmt2->fetch()) {
                $AjaxOptGpPosts []= [
                    'id'    => $fld_id2,
                    'label' => $fld_title2
                ];
            }
        }

        $stmt2->free_result();
        $stmt2->close();

        $AjaxOptGpLabel [] = [
            $fld_label,
            $AjaxOptGpPosts
        ];

    }

    echo json_encode($AjaxOptGpLabel);
}
/* free and close */
$stmt->free_result();
$stmt->close();

$conn -> close();

JSON输出

[
    ["AP", [{
        "id": 88,
        "label": "a"
    }, {
        "id": 1,
        "label": "AP - Invoices"
    }, {
        "id": 79,
        "label": "AP - Supplier Reports"
    }]],
    ["AR", [{
        "id": 2,
        "label": "AR - Customers"
    }, {
        "id": 3,
        "label": "AR - Interface Lines"
    }, {
        "id": 4,
        "label": "AR - Transactions"
    }]]
]

的jQuery

我对使用jQuery循环JSON以将值附加到SELECT菜单有点熟悉 - 例如

$(document).ready(function() {
    $('#cat_parent').change(function() {
        var currentValue = $(this).val();
        // Populate Categories once select Parent
        $.get("../ajax/ajax-cats-from-parent.php", {'cat_parent': currentValue}, function(data) {
            var cat_id = $.parseJSON(data);
            $('#cat_id').empty();
            for (var i = 0; i < cat_id.length; i++) {
                var regionOption = '<option value="'+cat_id[i]['id']+'">';
                regionOption += cat_id[i]['label'];
                regionOption += '</option>';
                $('#cat_id').append(regionOption);
            }
        });

    });
});

但我很难尝试调整上面使用的方法从上面的JSON输出生成这种类型的HTML:

<optgroup label="AP">
    <option value="88">a</option>
    <option value="1">AP - Invoices</option>
    <option value="798">AP - Supplier Reports</option>
</optgroup>
<optgroup label="AR">
    <option value="2">AR - Customers</option>
    <option value="3">AR - Interface Lines</option>
    <option value="4">AR - Transactions</option>
</optgroup>

任何建议都非常感谢。感谢

1 个答案:

答案 0 :(得分:0)

你可以这样做FIDDLE

var output = '[["AP",[{"id":88,"label":"a"},{"id":1,"label":"AP - Invoices"},{"id":79,"label":"AP - Supplier Reports"}]],["AR",[{"id":2,"label":"AR - Customers"},{"id":3,"label":"AR - Interface Lines"},{"id":4,"label":"AR - Transactions"}]]]';

$(document).ready(function() {
  var cat_id = $.parseJSON(output);
  console.debug(cat_id);
  $('#cat_id').empty();
  $.each(cat_id, function(index, data) {
    console.debug(data);
    var grpData = "<optgroup label=" + data[0] + ">";
    $.each(data[1], function(index2, subData) {
      grpData += "<option value="+subData.id+">"+data[0] +" - "+subData.label+"</option>";
    });
    grpData += "</optgroup>";
    $('#cat_id').append(grpData);
  });
});