【发布时间】:2021-10-05 21:07:43
【问题描述】:
我正在 JSON 中创建嵌套(分层)组。结构很简单——grand parent -> parent -> child:
main
secondary
mcondition
这是使用下面的 MySQL/PHP 来格式化main -> mcondition。
我应该如何更改它以在 main 和 mcondition 之间添加第二级(“次要”,例如父级)?
次要的列是mcondition.secondary
$query = 'SELECT * FROM mcondition ORDER BY mcondition.main ASC';
$result = $connection->query( $query );
$results = array();
$temp = array();
while ($line = mysqli_fetch_array($result)) {
$results[] = $line;
}
foreach($results as $row) {
$temp[$row['main']]['text'] = $row['main'];
if(!isset($temp[$row['main']]['children'])) {
$temp[$row['main']]['children'] = array();
}
array_push($temp[$row['main']]['children'], array(
'id' => $row['mcondition_pk'],
'text' => $row['mcondition_name']
));
}
$temp = array_values($temp);
echo json_encode($temp);
这是 JSON 目前的样子:
[
{
"text": "Main Heading 1",
"children": [
{
"id": "1",
"text": "mcondition_1"
},
{
"id": "17",
"text": "mcondition_4"
}
]
},
{
"text": "Main Heading 2",
"children": [
{
"id": "49",
"text": "mcondition_2"
},
{
"id": "48",
"text": "mcondition_5"
}
]
},
{
"text": "Main Heading 3",
"children": [
{
"id": "68",
"text": "mcondition_3"
},
{
"id": "67",
"text": "mcondition_6"
}
]
}
]
这是表mcondition的结构:
+---------------+------------+------+-----------+
| mcondition_pk | mcondition | main | secondary |
+---------------+------------+------+-----------+
mcondition 列是唯一的。
【问题讨论】:
-
我对输出 json 应该是什么样子有点困惑。也许您可以提供所需 json 项目的样本,以及源数据库表或其结构的样本。我也不清楚为什么你不一次创建临时数组的每个项目,而不是使用 isset 检查子元素是否存在,如果不存在则创建它,然后将 mcondition_ 推送给它。主要是独一无二的吗?如果这不是重复项应该发生的事情?如果是那么我不知道检查是否必要,只需一次创建整个数组元素。
-
@ChrisStricland 查看更新的 OP。 mcondition 是唯一的,在 Select2 中总是有祖父(主)和父(次)标题
-
@IlludiumPu36 您可以添加您正在寻找的预期 JSON 吗?
标签: php mysql jquery-select2