循环通过多维关联数组并输出结果[关闭]

Basically, I'm trying to loop through all the posts and find their appropriate tags. The $id variable is an array of all the post id's returned. So the first for loop should be finding all the tags for the posts and if there aren't any for that post set the tags to 0 (for $post_tags['THIS IS THE POST ID'])

It all seems to be fine for if there are no tags for a post and it will simply print 'No specified tags' once alongside with it (as expected). But, what seems to be happening is that the tags printed are all the tags from the appropriate post PLUS the ones from the previous posts returned. It seems to be adding onto what has been returned already.

I honestly don't see why it's doing this and considering there is no error coming up I find it hard to address. Any help or guidance would be greatly appreciated!

if($stmt = $mysqli->prepare("SELECT username, avatar FROM members WHERE id = ? LIMIT 1")){                          
// Get the posts tags
if($tgs = $mysqli->prepare("SELECT tag FROM tags WHERE post_id = ?")){
    for($i = 0; $i < count($id); $i++){
        $tgs->bind_param('i', $id[$i]);
        $tgs->execute();
        $tgs->store_result();
        $tgs->bind_result($tag);
        while($tgs->fetch()){
            $tags[] = $tag;
        }
        if($tgs->num_rows > 0){
            $post_tags[$id[$i]] = $tags;
        }else{
            $post_tags[$id[$i]] = 0;
        }
    }
    $tgs->close();
    for($i = 0; $i < count($id); $i++){             
        $stmt->bind_param('i',$by[$i]);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($username, $avatar);
        $stmt->fetch();
        echo '<ul class="f_ul_subject" style="margin-top:3px">
                    <li class="f_cat_subject" style="font-size:10px;line-height:12px;">';
                            for($j = 0; $j  < count($post_tags[$id[$i]]); $j++){
                                if($post_tags[$id[$i]] != 0){
                                    echo '<a class="post_tag" href="http://localhost/Site/NetPerry/forum/search.php?v=' . $post_tags[$id[$i]][$j] . '&amp;tags=true">
                                            <span>' . $post_tags[$id[$i]][$j] . '</span>
                                        </a>';
                                }else{
                                    echo 'No specified tags';
                                }
                            }
                    echo '</li>
                </ul>                                                       
            </li>';
    }
}

}

$tags[] = $tag; is filling up the array without ever emptying it. This is why the tags keep piling up. You can solve this by declaring the array empty before the fetch loop, like this:

$tags = array();
while($tgs->fetch()){
...