【问题标题】:Looping through multidimensional associative arrays and outputting results [closed]循环遍历多维关联数组并输出结果
【发布时间】:2013-07-05 18:04:42
【问题描述】:

基本上,我正在尝试遍历所有帖子并找到它们合适的标签。 $id 变量是返回的所有帖子 ID 的数组。因此,第一个 for 循环应该是查找帖子的所有标签,如果该帖子没有任何标签,请将标签设置为 0(对于 $post_tags['THIS IS THE POST ID'])

如果帖子没有标签,这一切似乎都很好,它只会在旁边打印“没有指定的标签”(如预期的那样)。但是,似乎正在发生的事情是,打印的标签是来自相应帖子的所有标签加上之前返回的帖子中的标签。它似乎正在添加已经返回的内容。

老实说,我不明白为什么会这样,考虑到没有出现错误,我觉得很难解决。任何帮助或指导将不胜感激!

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; 是个问题
  • 当然,过于本地化的问题“在我的代码中找我的bug”。
  • 感谢您的回复,它让我朝着正确的方向前进,现在似乎可以工作了。尽管没有义务回复,但如果您认为“在我的代码中查找错误”不适合该站点,您将无法获得帮助。不过,谢谢你。

标签: php arrays mysqli associative-array multidimensional-array


【解决方案1】:

$tags[] = $tag; 正在填充数组而从未清空它。这就是标签不断堆积的原因。您可以通过在 fetch 循环之前将数组声明为空来解决此问题,如下所示:

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

【讨论】:

  • 我想知道为什么这个答案被接受了,因为它没有任何帮助
  • @YourCommonSense 需要详细说明吗?我不明白为什么
  • 可能我错了。我不认为每个帖子都会有不同的查询
  • 准备好的查询可以根据需要重复使用。虽然我不得不承认代码结构有点不寻常。
猜你喜欢
  • 1970-01-01
  • 2012-05-26
  • 1970-01-01
  • 2013-04-01
相关资源
最近更新 更多