gpt4 book ai didi

php - JQuery Select2 - 从 PHP/MySQL 结果中格式化嵌套列表

转载 作者:行者123 更新时间:2023-11-29 09:32:29 25 4
gpt4 key购买 nike

我有一个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);

关于php - JQuery Select2 - 从 PHP/MySQL 结果中格式化嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58391169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com