我希望有人能帮我.
以下是我的查询:
$query_articles = mysql_query("SELECT * FROM articles ORDER BY article_date DESC LIMIT 30") or die(mysql_error());
$row_articles = mysql_fetch_assoc($query_articles);我想做的是展示所有30个结果,但我希望它是这样的:
// Show article #1
// Then loop through articles 2-7
// Then show article #8
// Then loop through articles 9-30原因是我对上面列出的每一组都有不同的格式。我可以很容易地进行单独的查询,但这并不理想,而且它会在之后搞砸我的分页。
那么,我如何使用这个查询执行这些循环呢?任何帮助都将不胜感激!谢谢。
/更新/
好的,这就是我现在拥有的,它给出了我想要的,但是它也显示了行31-42 (在我的DB中现在根本不存在):
$query_articles = mysql_query("SELECT * FROM articles ORDER BY article_date DESC LIMIT 32") or die(mysql_error());
$row_articles = mysql_fetch_assoc($query_articles);
$shown_articles = array(1, 8);
$article_index = 1;
foreach ($row_articles as $article) {
do {
if (in_array($article_index, $shown_articles)) {
echo '<p>'.$article_index.' ';
echo $row_articles['title'];
echo '</p>';
} else {
echo '<p>'.$article_index.' ';
echo $row_articles['title'];
echo '</p>';
}
$article_index++;
} while($row_articles = mysql_fetch_assoc($query_articles));
}知道为什么会出现额外的争吵吗?而且,如果我使用mysql_fetch_array,它会上升到第55行。
/更新/
这是我的最后一段代码,如果其他人需要的话。我还添加了另一个条件,因为我还想分隔9-30行。
$query_articles = mysql_query("SELECT * FROM articles ORDER BY article_date DESC LIMIT 32") or die(mysql_error());
$shown_articles = array(1, 8);
$article_range = range(9, 30);
$article_index = 1;
while($row_articles = mysql_fetch_assoc($query_articles)) {
if (in_array($article_index, $shown_articles)) {
echo '<p>'.$article_index.' ';
echo $row_articles['title'];
echo '</p>';
} elseif (in_array($article_index, $article_range)) {
echo '<p>'.$article_index.' ';
echo $row_articles['title'];
echo ' - 9-30</p>';
} else {
echo '<p>'.$article_index.' ';
echo $row_articles['title'];
echo ' - 2-7</p>';
}
$article_index++;
}发布于 2012-09-29 16:05:26
首先根据结果创建一个迭代器:
$rows = new ArrayIterator($row_articles);然后,要防止迭代器倒带:
$articles = new NoRewindIterator($rows);这可以帮助您创建子迭代器(例如,对于您的列表),使其不再倒带,而是继续。
然后你可以做你认为合适的手术:
foreach ($articles as $i => $article)
{
switch ($i)
{
case 1:
article_display($article);
article_list(new LimitIterator($articles, 0, 6));
break;
case 8:
article_display($article);
article_list(new LimitIterator($articles, 0, 21));
break;
default:
throw new Excpetion(sprintf("Unexpected i: %d", $i));
}
}注意:$i可能是基于零的,那么您需要更改case语句中的硬编码数字,就像我编写的基于1的语句一样。但我觉得你知道这个主意。
发布于 2012-09-29 15:59:59
您可以使用模算子来实现这一点:
$query_articles = mysql_query("SELECT * FROM articles ORDER BY article_date DESC LIMIT 30") or die(mysql_error());
$row_articles = mysql_fetch_assoc($query_articles);
$i=0;
foreach($row_articles as $article) {
if($i % 8 == 0) {
// do stuff for row 0, 8 ..
}
else {
// do stuff for other rows
}
$i++;
}发布于 2012-09-29 15:59:25
$shown_articles = array(1, 8);
$article_index = 1;
foreach ($row_article as $article) {
if (in_array($article_index, $shown_articles)) {
// Show article
} else {
// Do something else
}
$article_index++;
}https://stackoverflow.com/questions/12654185
复制相似问题