2012-02-07 74 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"; 
    } 
}