简体   繁体   English

jquery - JSON 对象,格式为<optgroup > , 由 P​​HP 和 MySQL 的 AJAX 返回在 Select2 中不起作用

[英]jquery - JSON object, formatted for <optgroup >, returned by AJAX from PHP and MySQL doesn't work in Select2

I spent a whole day trying to make a PHP script that convert MySQL Query results into a JSON object for <optgroup> in Select2, and when I finally found the solution, it does not work (there is nothing in Select2 dropdown menu).我花了一整天试图制作一个 PHP 脚本,将 MySQL 查询结果转换为 Select2 中<optgroup>的 JSON 对象,当我最终找到解决方案时,它不起作用(Select2 下拉菜单中没有任何内容)。 I am just a beginner in the whole programming thing, and I really do not have an idea how to solve this problem.我只是整个编程领域的初学者,我真的不知道如何解决这个问题。 The other answers on Stack didn't really help me. Stack 上的其他答案并没有真正帮助我。 This is what I got so far:这是我到目前为止得到的:

PHP PHP

$gardinersClasses = array(
    "A. Man and his Occupations",
    "B. Woman and her Occupations",
    "C. Anthropomorphic Deities",
    "D. Parts of the Human Body",
    ...etc.
);

$results = array();
$data = array();
$rowNumber = mysqli_num_rows($fetchData);

if ($rowNumber > 0) {
    while ($row = mysqli_fetch_array($fetchData, MYSQLI_ASSOC)) {
        $results[] = array(
            "id" => $row["id"],
            "text" => $row["hieroglyph_hieroglyphica_code"],
            "class" => $row["gardiners_class_id"]
        );
    }
    usort($results, function($a, $b) {
        $retVal = $a["class"] <=> $b["class"];
        if ($retVal == 0) {
            $retVal = strnatcmp($a["text"], $b["text"]);
        }
        return $retVal;
    });

    foreach($results as $result) {
        $gardinersClassNumber = $result["class"]-1;
        $gardinersClass = $gardinersClasses[$gardinersClassNumber];
        if (empty($data)) {
            $data[$gardinersClassNumber] = array(
                "text" => $gardinersClass,
                "children" => array(array(
                        "id" => $result["id"],
                        "text" => $result["text"]
                    )
                )
            );
        } else {
            $counter = 0;
            foreach ($data as $subdata) {
                if (in_array($gardinersClass, $subdata)) {
                    $counter++;
                }
            }
            if ($counter < 1) {
                $data[$gardinersClassNumber] = array(
                    "text" => $gardinersClass,
                    "children" => array(array(
                            "id" => $result["id"],
                            "text" => $result["text"]
                        )
                    )
                );
            } else {
                $data[$gardinersClassNumber]["children"][] = array(
                    "id" => $result["id"],
                    "text" => $result["text"]
                );
            }
        }
    }
}

echo json_encode($data);
exit();

JSON (received by AJAX) JSON (由 AJAX 接收)

{
"0": {
    "text": "A. Man and his Occupations",
    "children": [{
        "id": 1080,
        "text": "A1A"
    }, {
        "id": 1077,
        "text": "Hgn4"
    }, {
        "id": 1078,
        "text": "Hgn5"
    }]
},
"10": {
    "text": "L. Invertebrata and Lesser Animals",
    "children": [{
        "id": 1076,
        "text": "877"
    }, {
        "id": 1079,
        "text": "Hgn6"
    }]
},
"11": {
    "text": "M. Trees and Plants",
    "children": [{
        "id": 1074,
        "text": "9"
    }]
},
"13": {
    "text": "NL. Nomes of Lower Egypt",
    "children": [{
        "id": 1081,
        "text": "A1B"
    }]
},
"28": {
    "text": "Hgn. Hieroglyphicon Unclassified",
    "children": [{
        "id": 1072,
        "text": "Hgn1"
    }, {
        "id": 1073,
        "text": "Hgn2"
    }, {
        "id": 1075,
        "text": "Hgn3"
    }]
}
}

JQuery & Select2 JQuery & Select2

function hieroglyphSelectMimic(selectionField, phpScript, picture = false) {
function formatItem(item) {
    if (!item.id) {
        return item.text;
    }
    if (item.id == "x") {
        return $("<span class='select-option-hieroglyph grey-text text-14'>" + item.text + "</span>");
    } else {
        if (!picture) {
            return item.text;
        } else {
            return $("<span class='select-option-hieroglyph'><img class='hieroglyph-intext' src='./images/hieroglyphs/" + item.text + ".svg' onerror='this.src=\"./images/hieroglyphs/unknown.svg\"'> " + item.text + "</span>");
        }

    }
}
selectionField.select2({
    ajax : {
        url : phpScript,
        type : "POST",
        dataType : "json",
        delay : 350,
        data : function(params){
            return {
                term : params.term
            };
        },
        processResults : function(response) {
            return {
                results : response
            };
        },
        cache : true
    },
    templateResult : formatItem,
    language: {
        noResults: function (params) {
            return "Entered code doesn't exists.";
        }
    }
});
}

HTML HTML

<select id="js-hieroglyph-hieroglyphica-code-select" name="hieroglyph-hieroglyphica-code-select" class="dropdown-style" data-width="100%">
    <option value="" disabled selected>Select hieroglyph code</option>
</select>
<script>
    var hieroglyphCodeSelect = $("#js-hieroglyph-hieroglyphica-code-select");
    phpScript = "./includes/individual_retrieve_scripts/retrieve_hieroglyphs_undefined.script.php";
    hieroglyphSelectMimic(hieroglyphCodeSelect, phpScript);
</script>

Any help would be highly appreciated.任何帮助将不胜感激。

I found the solution accidentally.我无意中找到了解决方案。 The problem was in key in the $data array which was created purposely with $gardinersClassNumber .问题是在key的在$data ,将其用特意制作的磁盘阵列$gardinersClassNumber It should be automatically generated.它应该是自动生成的。

This is the correct solution:这是正确的解决方案:

foreach($results as $result) {
    $gardinersClassNumber = $result["class"]-1;
    $gardinersClass = $gardinersClasses[$gardinersClassNumber];
    if (empty($data)) {
        $data[] = array(
            "text" => $gardinersClass,
            "children" => array(array(
                    "id" => $result["id"],
                    "text" => $result["text"]
                )
            )
        );
    } else {
        $counter = 0;
        foreach ($data as $subdata) {
            if (in_array($gardinersClass, $subdata)) {
                $counter++;
            }
        }
        if ($counter < 1) {
            $data[] = array(
                "text" => $gardinersClass,
                "children" => array(array(
                        "id" => $result["id"],
                        "text" => $result["text"]
                    )
                )
            );
        } else {
            $currentKey = key($data);
            $data[$currentKey]["children"][] = array(
                "id" => $result["id"],
                "text" => $result["text"]
            );
        }
    }
}

As you can see, I used key() function to retrieve the current key when the match is found in the array, and then I am using it to insert data in that place.如您所见,当在数组中找到匹配项时,我使用key()函数来检索当前键,然后我使用它在该位置插入数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM