我向我的網站展示了它,並且它在FrontPage中推出了五篇帶有大圖的文章。問題是我需要這5個div始終填充一些文章數據,但我目前只有兩篇文章。所以我認爲,如果查詢返回5行以下,那麼我可以使用上一篇文章數據填充所有剩餘的點。但是,做到這一點的最佳方式是什麼?PHP - 回聲最後一行直到達到想要的數量
我的第一次嘗試是查詢結果到數組並檢查行數,然後使用arraypush複製最後一行,而數組行數達到5,但它太難看了。
我向我的網站展示了它,並且它在FrontPage中推出了五篇帶有大圖的文章。問題是我需要這5個div始終填充一些文章數據,但我目前只有兩篇文章。所以我認爲,如果查詢返回5行以下,那麼我可以使用上一篇文章數據填充所有剩餘的點。但是,做到這一點的最佳方式是什麼?PHP - 回聲最後一行直到達到想要的數量
我的第一次嘗試是查詢結果到數組並檢查行數,然後使用arraypush複製最後一行,而數組行數達到5,但它太難看了。
隨着你循環,你可以做一個計數。如果計數小於5,則可以使用數組中的最後一個元素創建一個for循環,for循環的長度是5減去您使用的計數。
例如
$count = 0;
$last_element = array();
foreach ($array as $arr) {
$count++;
$last_element = $arr;
echo $arr['title'];
}
if ($count < 5) {
for ($i = 0 ; $i < (5 - $count) ; $i++) {
echo $last_element['title'];
}
}
首先,計算db中的所有行。
二,打印所有的現有數據。
如果行是不到五,運行FOR循環,直到總數達到5
<?php
$rows = $db->count();
while($row = $db->fetch_assoc()) {
print_article();
}
if($rows < 5) {
for($i=0;$i<(5-$rows);$i++) {
print_article();
}
}
在這裏提供一些評論,解釋發生了什麼。代碼傾銷(通常)不建議。 – rayryeng 2014-09-11 13:44:41
$articleCount = 0;
$articles = array(
'0'=>array('name'=>'test'),
'1'=>array('name'=>'test 2')); // only two articles inside array
$total = count($articles);
while($articleCount < 5)
{
$article = current($articles);
echo $article['name'];
$articleCount++;
if(!next($articles))
{
reset($articles); // here You can decide if You want to start from begining or:
// prev($articles); // take last? Do what You want
}
}
//Reperesenting your articles as an array
$articles = array("first article", "second article");
//Loop 5 times
for ($i = 0; $i < 5; $i++) {
echo "<div>";
//If array element exists, echo it out between the div
if (isset($articles[$i])) {
echo $articles[$i];
} else {
//if it doesn't exist get the last array element
echo $articles[count($articles)-1];
}
echo "</div>";
}
返回打印上一篇文章:
<div>first article</div>
<div>second article</div>
<div>second article</div>
<div>second article</div>
<div>second article</div>
可能你給我們提供了一些例子 – 2014-09-11 13:30:08