我有这个结果来自MYSQL; content_groups已经由TopicId订购的MYSQL返回。PHP循环和重建数组按值(主题)输出JSON
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调用以获取所有需要的内容组,然后通过相应的主题重新组织数组,但我正在努力弄清楚如何输出以获得期望的最终结果。
谢谢@mickmackusa我正在敲我的头......这似乎是一个非常干净的方式来做到这一点;比我一直试图去做的代码少得多。 –