我想创建一个类似popurls.com的网站,但我将使用存储在MySQL数据库中的静态数据。顺便说一句,我使用php/mysql
在每个列表中,我想显示大约10个链接(就像在popurls上一样)。在这种情况下,如果我有20个列表,我需要制作20个"for"循环(针对每个特定列表)
我的问题是;有没有更好的方法来打印20个列表,而不是在php中使用20个for循环。
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块都存储在一个由类别名称键控的数组中。要输出每个块,只需:
echo $all_items['category name'];
PHP的foreach
http://php.net/manual/en/control-structures.foreach.php
很大程度上取决于您的数据输入,但我可以想象这样的情况:
<?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;
}
您只需要两个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 />";
}
}
您可以从数据库中获取所有信息,并将其解析为一个数组,类似
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>
}
}
只需将链接存储在二维数组中。这样,您就必须在特定列表中创建1个外循环(在列表上迭代)和1个内循环在链接上迭代。
$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";
}
}