【发布时间】:2017-12-20 17:28:22
【问题描述】:
我从 MYSQL 得到这个结果; content_groups 已经从按 TopicId 排序的 MYSQL 返回。
Array
(
[0] => Array
(
[ContentGroupId] => 1
[TopicId] => 1
[TopicName] => Meditations
[ContentGroupName] => Guided Meditations 1
)
[1] => Array
(
[ContentGroupId] => 2
[TopicId] => 1
[TopicName] => Meditations
[ContentGroupName] => Guided Meditations 2
)
[2] => Array
(
[ContentGroupId] => 3
[TopicId] => 1
[TopicName] => Meditations
[ContentGroupName] => Guided Meditations 3
)
[3] => Array
(
[ContentGroupId] => 4
[TopicId] => 2
[TopicName] => Hypnosis
[ContentGroupName] => Hypnosis Programs 1
)
[4] => Array
(
[ContentGroupId] => 5
[TopicId] => 2
[TopicName] => Hypnosis
[ContentGroupName] => Hypnosis Programs 2
)
[5] => Array
(
[ContentGroupId] => 6
[TopicId] => 3
[TopicName] => Mindfulness
[ContentGroupName] => Mindfulness Guides 1
)
[6] => Array
(
[ContentGroupId] => 7
[TopicId] => 3
[TopicName] => Mindfulness
[ContentGroupName] => Mindfulness Guides 2
)
[7] => Array
(
[ContentGroupId] => 8
[TopicId] => 3
[TopicName] => Mindfulness
[ContentGroupName] => Mindfulness Guides 3
)
我正在尝试遍历此内容,以便按主题和 JSON 编码进行分组,如下所示:
topics: [
{
TopicId: 1,
TopicName: Mediations,
content_groups: [
{
ContentGroupId: 1,
TopicId: 1,
TopicName: "Mediations",
ContentGroupName: "Guided Meditations 1"
},
{
ContentGroupId: 2,
TopicId: 1,
TopicName: "Mediations",
ContentGroupName: "Guided Meditations 2"
},
{
ContentGroupId: 3,
TopicId: 1,
TopicName: "Mediations",
ContentGroupName: "Guided Meditations 3"
}
]
},
{
TopicId: 2,
TopicName: Hypnosis,
content_groups: [
{
ContentGroupId: 4,
TopicId: 2,
TopicName: "Hypnosis",
ContentGroupName: "Hypnosis Programs 1"
},
{
ContentGroupId: 5,
TopicId: 2,
TopicName: "Hypnosis",
ContentGroupName: "Hypnosis Programs 2"
}
]
},
{
TopicId: 3,
TopicName: Mindfulness,
content_groups: [
{
ContentGroupId: 6,
TopicId: 3,
TopicName: "Hypnosis",
ContentGroupName: "Mindfulness Guides 1"
},
{
ContentGroupId: 7,
TopicId: 3,
TopicName: "Hypnosis",
ContentGroupName: "Mindfulness Guides 2"
},
{
ContentGroupId: 8,
TopicId: 3,
TopicName: "Hypnosis",
ContentGroupName: "Mindfulness Guides 3"
}
]
}
]
我最初只是在循环每个主题以获取相应的内容组时进行了单独的 MYSQL 调用,但是随着主题的增长,这似乎效率低下,因为我可以更轻松地进行一次 SQL 调用以获取所有需要的内容组然后重建要按相应主题分组的数组,但我正在努力弄清楚如何输出它以获得所需的最终结果。
【问题讨论】: