2011-02-06 25 views
0

爆炸在我的索引文件,我得到使用此功能(這是在另一個文件中)數據庫中的數據:標記和在PHP

function get_all_threads($link, $start) 
{ 
    $threads = select_Query("SELECT thread.title, thread.id as t_id, 
          thread.content, author.username, author.id as a_id, 
          GROUP_CONCAT(DISTINCT tags.name ORDER BY tags.name DESC SEPARATOR ',') AS tags 
          FROM thread JOIN thread_tags ON thread.id = thread_tags.thread_id 
          JOIN tags ON thread_tags.tag_id = tags.id 
          INNER JOIN author on author.id = thread.author_id 
          GROUP BY thread.id DESC 
          LIMIT $start, 30", $link);  

    return $threads; 
} 

在我的索引文件的代碼如下:

$threads = get_all_threads($link, $start); 
    include FORUM_ROOT . 'html/main/threads.html.php'; 

在threads.html.php

<?php foreach ($threads as $thread): ?> 

<h1><?php echo $thread['title']; ?></h1> 
<?php echo $thread['content']; ?> 
<?php echo $thread['tags']; ?> <!-- All of these appear as one --> 

<?php endforeach; ?> 

正如你可以看到我得到的線程,它們的作者和他們的標籤。不過我使用GROUP_CONCAT的標籤,因此,當我要讓每一個人標籤的鏈接,如在threads.html.php:

<a href="?tag=<?php echo $thread['tags']; ?>" > 
    <?php echo $thread['tags']; ?> 
</a> 

所有標籤顯示爲一個鏈接,(例如,如果標籤是蘋果,橙,香蕉,他們將顯示爲apple, orange, banana,而不是appleorangebanana):

我知道分手了這些標籤,我可以使用爆炸,然後遍歷每個如下:

<?php $tags = array(); 
$tags = explode(',', $thread['tags']); 
?> 


(Tagged: 
<?php foreach ($tags as $tag): ?> 
<a href="/tag?=<?php echo $tag;?>"><?php echo $tag; ?></a> 
<?php endforeach; ?>) 

不過我將 那麼必須在threads.html.php中做到這一點,我想保持演示代碼分離。

在index.php中有這樣做的方法嗎?同時遍歷每個線程和爆炸的每個標籤將花費太長的時間對於那些超過30

編輯主題:

我的表結構如下:

線程,author_threads,作家,標籤,thread_tags,回覆和author_replies

1http://apple,橙,香蕉

+0

可以添加你的數據庫表結構 – 2011-02-06 17:45:17

+0

我想如果可能更喜歡問題簡單化......。 – Kissaki 2011-02-06 17:53:30

+0

我不認爲`GROUP_CONCAT`是SQL標準......您使用哪種DBS? – Kissaki 2011-02-06 17:56:12

回答

0

款待get_all_threads作爲模型的一部分 - 黑盒子 - 您不需要知道數據是如何獲取的(是SQL查詢,xml文件還是外部API調用)。你對數據不感興趣,僅此而已。

到目前爲止,不可能通過SQL查詢爲一個線程獲取多個標籤。即使你刪除了GROUP_CONCAT,你也會得到一個線程的一堆記錄,這些記錄也需要以某種方式解析。但根據第一段,你應該解析你的函數中的數據。

function get_all_threads($link, $start) 
{ 
    $threads = select_Query("SELECT thread.title, thread.id as t_id,.."); 

    //PHP 5.3 
    array_walk($threads, function(&$thread) { 
     $thread['tags'] = explode(',', $thread['tags']); 
    }); 

    //PHP < 5.3 
    foreach ($threads as &$thread) { 
     $thread['tags'] = explode(',', $thread['tags']); 
    } 


    return $threads; 
} 

當你這樣做的,你的演示代碼將是乾淨的。

0

您想要爲每個線程獲取並打印多個標籤。那麼,爲什麼你在一個查詢中做到這一點?而不是做你會一個龐大的查詢:

SELECT thread.title, thread.id as t_id, thread.content, 
     author.username, author.id as a_id, 
INNER JOIN author ON author.id = thread.author_id 
ORDER BY thread.id DESC 
LIMIT $start, 30 

,併爲每個線程

SELECT tags.name 
FROM thread_tags 
WHERE thread_tags.thread_id == $id 

存儲那些在數據結構,並把它傳遞給你的演示文稿模板(比如你與你對答現在做的)。

(哇靠,這是一個複雜的查詢...... 看起來好多了爲好,對不對?所以更容易閱讀和理解!)

順便說一句,與GROUP BY thread.id DESC什麼?我確實希望你的ID是唯一的,或者更好的是主鍵!那麼不需要GROUP BY!