【发布时间】:2016-04-18 18:13:50
【问题描述】:
我正在使用 PHP 从 DB 中回显我的产品。如果我们只使用 foreach 将得到每个循环一个项目的结果,但实际上我希望它每次回显两个项目,如下函数
这是我使用 foreach 从数据库中获取数据的 PHP 函数
我使用 row item 选择器来包装 product 选择器,所以我想回显 product 两次,然后它会回显 row item。
示例:行项目 = 1 然后 产品 = 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;
}
此函数将在循环中回显一个项目。
【问题讨论】:
-
您必须添加一堆
if()代码来检测您正在进行的迭代,并根据需要输出“脚手架”html。例如if ($row is odd) { start new div} output stuff; if ($row is even) { end new div}. -
我已经测试过 if($k$2 ==0){} 但不行