[英]jquery - How to add image to the Select2 dropdown list with data retreived from MySQL and PHP through AJAX?
[英]JQuery Select2 - Format nested list from PHP/MySQL results
我有一个Select2列表,我想用数据的嵌套结构填充它:
Level 1
Condition 1
Condition 2
Level 2
Condition 3
Condition 4
etc
JSON 需要采用以下格式:
data: [{
'text': 'Level 1',
'children': [{
'id': 1,
'text': 'Condition 1'
}, {
'id': 2,
'text': 'Condition 2'
}, ],
'text': 'Level 2',
'children': [{
'id': 3,
'text': 'Condition 3'
}, {
'id': 4,
'text': 'Condition 4'
}, ]
}]
JQuery Select2:
$.ajax( {
url: "scripts/get_conditions.php",
dataType: 'json'
} ).then( function ( response ) {
$( "#condition_tree" ).select2( {
placeholder: "Select a Condition...",
allowClear: true,
width: 'resolve',
containerCssClass: "show-hide",
data: response
} );
} );
目前使用以下 PHP 和 MySQL 我不确定如何更改以产生所需的结果:
$query = 'SELECT * FROM mcondition ORDER BY mcondition_name ASC';
$result = $connection->query( $query );
$presentations = array();
while ($row = mysqli_fetch_array($result)) {
$mconditions[] = array("id"=>$row['mcondition_pk'], "text"=>$row['mcondition_name']);
}
echo json_encode($mconditions);
?>
和 mcondition 表:
+---------+-----------+------------------------------+
| mcondition_pk | mcondition_name | mcondition_level |
+---------+-----------+------------------------------+
| 1 | Condition 1 | Level 1 |
+---------+-----------+------------------------------+
| 2 | Condition 2 | Level 1 |
+---------+-----------+------------------------------+
| 3 | Condition 3 | Level 2 |
+---------+-----------+------------------------------+
| 4 | Condition 4 | Level 2 |
+---------+-----------+------------------------------+
注意 PHP 版本为 5.3.3,目前没有升级机会。
使用级别名称作为二维数组的键来收集您的数据,将每一行的数据添加到相应键下的子项中。
// fake mysql row data
$data = [
['mcondition_pk' => 1, 'mcondition_name' => 'Condition 1', 'mcondition_level' => 'Level 1'],
['mcondition_pk' => 2, 'mcondition_name' => 'Condition 2', 'mcondition_level' => 'Level 1'],
['mcondition_pk' => 3, 'mcondition_name' => 'Condition 3', 'mcondition_level' => 'Level 2'],
['mcondition_pk' => 4, 'mcondition_name' => 'Condition 4', 'mcondition_level' => 'Level 2'],
];
$temp = [];
// foreach loop over fake data, replace that with your original `while(…)` again
foreach($data as $row) {
$temp[$row['mcondition_level']]['text'] = $row['mcondition_level'];
$temp[$row['mcondition_level']]['children'][] = [
'id' => $row['mcondition_pk'],
'text' => $row['mcondition_name']
];
}
// replace the associative keys with simple numeric ones again
$temp = array_values($temp);
echo json_encode($temp);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.