简体   繁体   English

从PHP循环创建嵌套数组

[英]create nested arrays from PHP loop

I need to create nested arrays here where there is an array that contains each $forum_topic_name , and then within that array, I need to list each associated $subtopic_name 我需要在此处创建嵌套数组,其中有一个包含每个$ forum_topic_name的数组,然后在该数组中,我需要列出每个关联的$ subtopic_name

$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']; 
    }
}

My ultimate goal is to encode it as JSON so I can display the following: 我的最终目标是将其编码为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...

there are can be several options, but you can go with: 可以有几种选择,但是您可以选择:

$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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM