在我的for循环中,可以打印出列名,以得到名称重复以及由于某种原因而产生的数字。
$q = "SELECT products.name, products.price, products.amount, categories.category_name
FROM products
LEFT JOIN categories ON (products.category_id = categories.category_id)";
<table class="table">
<thead>
<tr>
<?php while ($row = mysqli_fetch_array($query)) {
foreach ($row as $key => $value) {
echo "<th scope='col'>$key</th>";
}
} ?>
</tr>
</thead>
我的表中有3种产品,我得到3个列名的重复项
答案 0 :(得分:1)
如果要使用动态列名,则可以将数据存储到新数组中,然后可以使用此数组两次,一次用于标题,一次用于值。
$newArray = array(); // initiliaze
while ($row = mysqli_fetch_assoc($result)) { // here i am using mysqli_fetch_assoc
$newArray[] = $row; // store in a new array
}
然后,您的标题为:
$i = 1;
foreach ($newArray as $value) {
if($i > 1) continue; // will use for ist iteration only.
foreach ($value as $key => $Fvalue) {
echo "<th scope='col'>".$key."</th>"; // will print headings
}
$i++;
}
然后您可以将值显示为:
foreach ($newArray as $value) {
foreach ($value as $key => $Fvalue) {
echo "<td>".$Fvalue."</td>"; // will show all values.
}
}