猿问

如何使用 PHP 将表格垂直旋转

我只是在学习 PHP,我想创建一个表来显示我提交到我的数据库的回显数据,我的问题是默认情况下该表水平显示,正如您在我的脚本中看到的 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>

但我希望它垂直回显,而不是像我想要的垂直结果,我试图在我的 PHP 代码中更改回显中的 html,但我根本无法获得结果,而且表格的形状与我想要的相差甚远这是我页面的完整脚本。



呼如林
浏览 121回答 2
2回答

慕的地8271018

正如其他人所说,您应该将水平阵列转换为垂直阵列。当然,它应该是一个通用函数来转换任何查询结果,而不是对行标题进行硬编码。这个想法是获取每一行的数组键并将它们用作新数组的键,然后将每个对应的值添加到新数组项。这是在 mysqli 中的实现方式:<?phpmysqli_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()) {&nbsp; &nbsp; foreach(array_keys($row) as $key) {&nbsp; &nbsp; &nbsp; &nbsp; $data[$key][] = $row[$key];&nbsp; &nbsp; }}然后你得到一个具有所需结构的数组,你可以使用 ROOT 答案中的代码输出它:<table border="1">&nbsp; <?php foreach($data as $key => $val): ?>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td><?= $key ?></td>&nbsp; &nbsp; &nbsp; <?php foreach($val as $field): ?>&nbsp; &nbsp; &nbsp; &nbsp; <td><?= $field ?></td>&nbsp; &nbsp; &nbsp; <?php endforeach ?>&nbsp; &nbsp; </tr>&nbsp; <?php endforeach ?></table>

慕雪6442864

我将您的数据模拟到普通数组中,我使用了一个 while 循环来创建一个新的Array并创建我们需要能够将列翻转为行的格式,这就是我认为您想要的:<?php$users&nbsp; = [&nbsp; [&nbsp; &nbsp; 'name'=> 'James',&nbsp; &nbsp; 'height'=> 1.75,&nbsp; &nbsp; 'age'=> 18,&nbsp; ],&nbsp; [&nbsp; &nbsp; 'name'=> 'Bill',&nbsp; &nbsp; 'height'=> 170,&nbsp; &nbsp; 'age'=> 16,&nbsp; ]];$newArr = [];foreach($users as $key => $val) {&nbsp; $newArr['name'][$i] = $val['name'];&nbsp; $newArr['age'][$i] = $val['age'];&nbsp; $newArr['height'][$i] = $val['height'];&nbsp; $i++;}?><table border="1">&nbsp; <?php foreach($newArr as $key => $val): ?>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td><?php echo $key; ?></td>&nbsp; &nbsp; &nbsp; <?php foreach($val as $field): ?>&nbsp; &nbsp; &nbsp; &nbsp; <td><?php echo $field; ?></td>&nbsp; &nbsp; &nbsp; <?php endforeach; ?>&nbsp; &nbsp; </tr>&nbsp; <?php endforeach ?></table>
随时随地看视频慕课网APP
我要回答