Mysqli 如何用 3 列获取和填充数据
我有一张桌子.我的表如下所示.
I have a table. My table like below.
id | product_name | price
我有列表视图.我想像这样获取数据并填写.
and i have list view. I want to get data and fill like this.
<div class="container">
<div class="row">
<div class="col s4">product_name (first)</div>
<div class="col s4">product_name (second)</div>
<div class="col s4">product_name (third)</div>
</div>
<div class="row">
<div class="col s4">product_name (fourth)</div>
<div class="col s4">product_name (fifth)</div>
<div class="col s4">product_name (sixth)</div>
</div>
</div>
我该怎么做?
我尝试使用 mysqli_fetch_assoc,但我想从我的表中填充已排序数据的行中的列.
I try mysqli_fetch_assoc but I want to fill columns in the rows ordered data from my table.
推荐答案
您可以通过使用 模运算符.
<?php
$result = [
['id' => 1, 'product_name' => 'a'],
['id' => 2, 'product_name' => 'b'],
['id' => 3, 'product_name' => 'c'],
['id' => 4, 'product_name' => 'd'],
['id' => 5, 'product_name' => 'e'],
['id' => 6, 'product_name' => 'f'],
['id' => 7, 'product_name' => 'g'],
['id' => 8, 'product_name' => 'h'],
['id' => 9, 'product_name' => 'i'],
['id' => 10, 'product_name' => 'j'],
];
?>
<div class="container">
<?php foreach ($result as $key => $value) {
if ($key % 3 == 0) { // change 3 to how many items between rows
if ($key != 0) { echo '</div>'.PHP_EOL; }
echo '<div class="row">'.PHP_EOL;
}
echo '<div class="col s4">'.$value['product_name'].'</div>'.PHP_EOL;
}
?>
</div>
</div>
https://3v4l.org/vKrf9
结果:
<div class="container">
<div class="row">
<div class="col s4">a</div>
<div class="col s4">b</div>
<div class="col s4">c</div>
</div>
<div class="row">
<div class="col s4">d</div>
<div class="col s4">e</div>
<div class="col s4">f</div>
</div>
<div class="row">
<div class="col s4">g</div>
<div class="col s4">h</div>
<div class="col s4">i</div>
</div>
<div class="row">
<div class="col s4">j</div>
</div>
</div>
相关文章