如何使用 PHP 使 table 垂直

How to turn a table vertical using PHP

我正在学习 PHP,我想创建一个 table 来显示我提交到我的数据库的回显数据,我遇到的问题是 table 水平显示默认情况下,如您所见 Horizontal default table 这是我的脚本

<table >
<tr>
<th>Name</th>
<th>Age</th>
<th>Height</th>
</tr>
<?php
$conn = mysqli_connect("localhost", "root", "", "class");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Name, Age, Height FROM student order by Name desc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Name"]. "</td><td>" . $row["Age"] . "</td><td>"
. $row["Height"]. "</td></tr>";
}
echo "</table>";
} else //{ echo "0 results"; }//
$conn->close();
?>
</table>

但我希望它像这样垂直回显 VERTICAL RESULT I WANT and I tried to change html in echo in my PHP code but I can't get the result at all and the shape of the table is far away from what I want and this is the full script of my page .

这不是个好主意!如果你有很多 ROW 你会生成一个长 table 用户在屏幕上不可见。

如果你想这样做,毕竟你可以改变 table 结构,但你不会尊重 html table 结构。

我给你一个

Dirty code

<table>
<tr>
<th>Name</th>
<?php foreach ($row as $value) { ?><td><?php echo$value["Name"];  ?></td>
<?php } ?>
</tr>

<tr>
<th>Age</th>
<?php foreach ($row as $value) { ?>
    <td><?php echo $value["Age"];  ?></td>
<?php } ?>
</tr>

<tr>
<th>Height</th>
<?php foreach ($row as $value) { ?>
    <td><?php echo $value["Height"];  ?></td>
<?php } ?>
</tr>
</table>

I recommand to USE CSS instead a table

我将您的数据模拟到普通数组中,我使用 while 循环创建了一个新的 Array 并创建了我们需要能够将列翻转为行的格式,这就是我对您的看法想要:

<?php
$users  = [
  [
    'name'=> 'James',
    'height'=> 1.75,
    'age'=> 18,
  ],
  [
    'name'=> 'Bill',
    'height'=> 170,
    'age'=> 16,
  ]
];


$newArr = [];

foreach($users as $key => $val) {
  $newArr['name'][$i] = $val['name'];
  $newArr['age'][$i] = $val['age'];
  $newArr['height'][$i] = $val['height'];
  $i++;
}


?>
<table border="1">
  <?php foreach($newArr as $key => $val): ?>
    <tr>
      <td><?php echo $key; ?></td>
      <?php foreach($val as $field): ?>
        <td><?php echo $field; ?></td>
      <?php endforeach; ?>
    </tr>
  <?php endforeach ?>
</table>

正如其他人所说,您应该将水平阵列转换为垂直阵列。

当然,它应该是一个通用函数,可以转换任何查询结果,而不是对行标题进行硬编码。这个想法是获取每一行的数组键并将它们用作新数组的键,然后将每个对应的值添加到新数组项。

这是在 mysqli 中的实现方式:

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect('127.0.0.1','root','','test');
$mysqli->query("set names 'UTF8'");

$data = [];
$res = $mysqli->query("SELECT Name, Age, Height FROM student order by Name desc");
while ($row = $res->fetch_assoc()) {
    foreach(array_keys($row) as $key) {
        $data[$key][] = $row[$key];
    }
}

然后你得到一个具有所需结构的数组,你可以使用 ROOT 答案中的代码输出它:

<table border="1">
  <?php foreach($data as $key => $val): ?>
    <tr>
      <td><?= $key ?></td>
      <?php foreach($val as $field): ?>
        <td><?= $field ?></td>
      <?php endforeach ?>
    </tr>
  <?php endforeach ?>
</table>