2010-04-24 100 views
0

过去几天一直试图让我的脑袋周围循环,但代码似乎效率非常低,我试图实现。我假设我过分复杂这一点,尽管我没有尝试过似乎工作。需要将相关ID添加到While循环(php)

我的论坛中的每个主题都可以将相关主题ID存储在单独的表中。帖子ID也存储在此表中,因为该特定帖子引用了它们被认为相关的原因。

数据库表中只包含:topic_idrelated_idpost_id

// Get related IDs and post IDs for current topic being viewed 
$result = $db->query('SELECT related_id, post_id FROM related_topics WHERE topic_id='.$id.''); 
    // If related topics found, put both of the IDs into arrays 
    if ($db->num_rows($result)) { 
     while($cur_related = mysql_fetch_array($result)){ 
      $reltopicarray[] = $cur_related['related_id']; 
      $relpost[] = $cur_related['post_id']; 
     } 

     // If the first array isnt empty, get some additional info about each related ID from another table 
     if(!empty($reltopicarray)) { 
      $pieces = $reltopicarray; 
      $glued = "\"".implode('", "', $pieces)."\""; 
      $fetchtopics = $db->query('SELECT id, subject, author, image, etc FROM topics WHERE id IN('.$glued.')'); 
     } 

     // Print each related topic   
     while($related = mysql_fetch_array($fetchtopics)){ ?> 

    <a href="view.php?id=<?php echo $related['id']; ?>"><?php echo $related['subject']; ?></a> by <?php echo $related['author']; ?> 

    // Id like to show the Post ID below (from the array in the first while loop) 
    // The below link doesnt work as Im outside the while loop by this point. 
    <br /><a href="view.php?post_id=<?php echo $cur_related['post_id']; ?>">View Relationship</a> 

<?php } ?> 

以上当前工作,不过我想也显示下面的每个相关主题链接post_id链接,如上图所示。

回答

0

如果你改变了第二while循环是这样的:

<?php 
$i = 0; 
while($related = mysql_fetch_array($fetchtopics)){ 
     //show view link 
     // [...] 

     //show the view related link 
     ?> 
     <a href="view.php?post_id=<?php echo $relpost[$i]['post_id']; ?>">View Relationship</a> 
     <?php 
     //increment the i so that you can get the next post in the next iteration of the loop 
     $i++; 
} 
?> 

[旁注] 你也许不应该做的数据库查询在相同的位置要生成的面向未来的HTML你的理智。 [/题外话]

[编辑]

你也可以做到这一切作为一个查询:

SELECT related_topics.related_id, 
     related_topics.post_id, 
     related_topics.topic_id, 
     topics.subject, 
     topics.author, 
     topics.image, 
     topics.etc 
FROM related_topics 
LEFT JOIN topics ON topics.id = related_topics.topic_id 
WHERE topic_id= $id 

那么你就只能通过它必须循环一次,所有的链接。

+0

这假定每个主题总是有$ relpost。 – SeanJA 2010-04-24 01:22:47

+0

编辑后的内容比第一个更好... – SeanJA 2010-04-24 01:28:47

+0

感谢您的努力,但单个查询版本与我最初的尝试类似。不幸的是,它总是抓住相同的主题主题(在WHERE id =中声明)。我首先需要获取相关的ID以便获得正确的主题。我会尽快尝试你的原始代码,谢谢:) – Ryan 2010-04-25 15:04:06