从PHP循环创建嵌套数组

时间:2013-11-12 02:07:55

标签: php arrays

我需要在这里创建嵌套数组,其中有一个包含每个 $ forum_topic_name 的数组,然后在该数组中,我需要列出每个关联的 $ subtopic_name < / p>

$find_forum_topics = mysqli_query($con, "SELECT * FROM forumTopics ORDER BY listValue ASC");

while ($find_forum_topics_row = mysqli_fetch_array($find_forum_topics)) {
    $forum_topic_name[] = $find_forum_topics_row['topicName'];

    $find_forum_subtopics = mysqli_query($con, "SELECT id, subTopicName FROM forumSubTopics WHERE topicID='$forum_topic_id' ORDER BY listValue ASC");

    while ($find_forum_subtopics_row = mysqli_fetch_array($find_forum_subtopics)) {
        $subtopic_name[] = $find_forum_subtopics_row['subTopicName']; 
    }
}

我的最终目标是将其编码为JSON,以便显示以下内容:

<div class="topic">
    <div class="topicname">Topic 1</div>
    <div class="subtopics">
        <div class="subtopicname">Subtopic 1</div>
        <div class="subtopicname">Subtopic 2</div>
    </div>
</div>
<div class="topic">
    <div class="topicname">Topic 2</div>
    <div class="subtopics">
        <div class="subtopicname">Subtopic 1</div>
        <div class="subtopicname">Subtopic 2</div>
    </div>
</div>
etc...

1 个答案:

答案 0 :(得分:0)

可以有多种选择,但您可以选择:

$find_forum_topics = mysqli_query($con, "SELECT * FROM forumTopics ORDER BY listValue ASC");

while ($find_forum_topics_row = mysqli_fetch_array($find_forum_topics)) {
    $topicName = $find_forum_topics_row['topicName']; // get topic name
    $forum_topic_name[$topicName] = array(); // use it as key to array

    $find_forum_subtopics = mysqli_query($con, "SELECT id, subTopicName FROM forumSubTopics WHERE topicID='$forum_topic_id' ORDER BY listValue ASC");

    while ($find_forum_subtopics_row = mysqli_fetch_array($find_forum_subtopics)) {
        $forum_topic_name[$topicName][] = $find_forum_subtopics_row['subTopicName']; // add sub topics
    }
}