【发布时间】:2019-10-15 09:13:18
【问题描述】:
我有一个 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,目前没有升级机会。
【问题讨论】:
-
您不能直接使用查询来执行此操作。您必须使用循环从结果中获取值,然后检查级别并在该循环中相应地将它们推送到该键中。
标签: php mysql jquery-select2