2012-02-07 139 views
1

我想製作一個類似popurls.com的網站,但我會使用存儲在MySQL數據庫中的靜態數據。順便說一句我使用php/mysql。
在每個列表中,我想顯示10個鏈接(就像在popurls上)。在這種情況下,如果我有20個列表,我需要爲'循環(每個特定列表)製作20'。
我的問題是;有沒有更好的方式來打印這20個列表,而不是在php中使用20'for'循環。多循環 - 如何打印數據

回答

0

一個for環或foreach循環將正常工作,但是這將是編碼少了很多,如果你只是建立一個單一的for循環和推送內容到一個數組的數組或字符串數​​組...然後你可以做任何你想要的實際內容(假設我們按照category的列進行分組,我將使用一個使用字符串數組的例子(並且我參考的查詢在這裏解釋:http://explainextended.com/2009/03/06/advanced-row-sampling/

$query = mysql_query([QUERY THAT GETS ALL ITEMS, BUT LIMITS BY EACH CATEGORY]) or die(mysql_error()); 
$all_items = array(); 
while($row=mysql_fetch_array($query)){ 
    if (!isset($all_items[$row['category']])){ //if it isn't created yet, make it an empty string 
     $all_items[$row['category']] = ""; 
    } 
    $all_items[$row['category']] .= "<li><a href='".$row['url']."'>".$row['title]."</a></li>"; //concatinate the new item to this list 
} 

現在我們有一個數組,其中每個部分的HTML塊存儲在一個arr按類別的名稱鍵入。要輸出每個塊,只需:

echo $all_items['category name']; 
0

取決於數據輸入了很多,但我能想象這樣的事情:

<?php 


$lists = arrray('list1', 'list2', 'list3'); 

foreach ($lists as $current) { 
    $data = fetch_data_from_mysql($current); 
    foreach ($data as $link) { 
     echo "<a href=\"$data\">Link</a>"; 
    } 
} 

function fetch_data_from_mysql($current) 
{ 
    $list_data = array(); 

    // do whatever is required to fetch the list data for item $current from MySQL 
    // and store the data in $list_data 

    return $list_data; 
} 
+0

當然,如果它是真實的,我會做它面向對象;) – 2012-02-07 14:16:50

0

你只需要兩個foreach循環。假設你從一個MySQL表中的數據(如你寫的),這可能是這樣的:

$list_query = mysql_query("SELECT * FROM lists";) 

while($list = mysql_fetch_array($list_query)) 
{ 
    echo "<h1>{$list['title']}</h1>"; 

    $query = mysql_query("SELECT * FROM entries WHERE list_id = {$list['id']}"); 

    while($entry = mysql_fetch_array($query)) 
    { 
     echo "- {$entry['name']}<br />"; 
    } 
} 
0

您可以從數據庫中獲取的所有信息,並將其解析到一個數組,像

array[<news type1>] = array(link1, link2, link3, etc); 
array[<news type2>] = array(link1, link2, link3, etc); 

,並在佈局上,你可以使用

foreach ($newsCategory AS $categoryLinks) { 
    foreach ($categoryLinks AS $newsLink) { 
     <show the link and/or extra data> 
    } 
} 
0

只是存儲你的鏈接在二維數組中。這樣,你將不得不做一個外部循環(迭代列表)和一個內部循環遍歷特定列表中的鏈接。

$links = array(
    'science' => array('link1', 'link2', ...), 
    'sports' => array('link1', 'link2'), 
    // ... and so on 
); 
foreach ($links as $category => $urls) { 
    echo "Links in category: $category\n"; 
    foreach ($urls as $url) { 
    echo $url . "\n"; 
    } 
}