如何通过使用PHP Foreach一次回显两个项目? [英] How to echo two items per one time by using PHP Foreach?
问题描述
我正在使用PHP从数据库中回显我的产品.如果我们仅使用foreach,则每个循环将获得一项结果,但是,实际上,我希望它每一次回显两项,如下所示
I'm using PHP to echo my products from DB. If we just use foreach will get the result one item per a loop but, Actually I want it echo two items per one times as below function
这是我的PHP函数,使用foreach从数据库中获取数据
This is my PHP function using foreach to fetch data from DB
我使用了 行项 选择器来包装 product 选择器,所以我想回显 产品 两次,它将回显 行项目 .
I've used row item selector to wrap product selector so I want to echo block of product two times then it will echo row item.
示例:行项目= 1,然后 产品 = 2
Example: row item = 1 then product = 2
public function last_upated_products() {
$data = $this->newest_products_from_db('products');
$out = '';
if ($data) {
foreach ($data as $k => $row) {
$out .= '<div class="row item">';
$out .= '<div class="product">';
$out .= '<div class="image">';
$out .= '<a href=""><img src="' . base_url('asset/img/main/9.jpg') . '" alt="img" class="img-responsive"></a>';
$out .= '<div class="promotion"><span class="discount">' . $row['prod_id'] . '% OFF</span> </div>';
$out .= '</div>';
$out .= '<div class="description"><div class="price"><span>$' . $row['prod_price'] . '</span></div><h4><a href="#">' . $row['prod_name'] . '</a></h4>';
$out .= '<p>' . $row['prod_descrip'] . '</p>';
$out .= '</div>';
$out .= '</div>';
$out .= '</div>';
}
}
return $out;
}
此功能将回显一项以循环.
This function will echo one item for a loop.
推荐答案
一次循环不能打印两次.您可以使用条件HTML
输出来完成此工作.
考虑一下:
You can not print two times in one iteration of loop. You can conditional HTML
output to do this job.
Consider this:
function last_upated_products() {
$data = $this->newest_products_from_db('products');
$out = '';
$counter = 1;
$length = count($data);
if ($data) {
foreach ($data as $k => $row) {
if ($counter % 2 != 0) {
$out .= '<div class="row item">';
}
$out .= '<div class="product">';
$out .= '<div class="image">';
$out .= '<a href=""><img src="' . base_url('asset/img/main/9.jpg') . '" alt="img" class="img-responsive"></a>';
$out .= '<div class="promotion"><span class="discount">' . $row['prod_id'] . '% OFF</span> </div>';
$out .= '</div>';
$out .= '<div class="description"><div class="price"><span>$' . $row['prod_price'] . '</span></div><h4><a href="#">' . $row['prod_name'] . '</a></h4>';
$out .= '<p>' . $row['prod_descrip'] . '</p>';
$out .= '</div>';
$out .= '</div>';
if ($counter % 2 == 0 || $length == $counter) {
$out .= '</div>';
}
$counter++;
}
}
return $out;
}
这篇关于如何通过使用PHP Foreach一次回显两个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!