gpt4 book ai didi

php - Foreach 行显示为列

转载 作者:搜寻专家 更新时间:2023-10-31 22:49:33 26 4
gpt4 key购买 nike

我有一个非常标准的数据库,例如:

id | name | last_name                | gender 
-----------------------------------------------
1 | John | Doe | Male
2 | Jane | Smith Dolores Clayborne | Female
3 | Paul | Paulson | Male

我想在表格中显示它,但数据库中的每一行都需要是 HTML 表格中的一列:

id        | 1         | 2         | 3      
---------------------------------------------
name | John | Jane | Paul
---------------------------------------------
last_name | Doe | Smith | Paulson
| | Dolores |
| | Clayborne |
---------------------------------------------
gender | Male | Female | Male

如果我去:

foreach($data as $row) {
echo "<tr><td>" . $row->id . "</td></tr>";
echo "<tr><td>" . $row->name . "</td></tr>";
echo "<tr><td>" . $row->last_name . "</td></tr>";
echo "<tr><td>" . $row->gender . "</td></tr>";
}

我在一长列中获取所有数据。如何在每个 SQL 行之后拆分列?

注意:$data 是一个对象数组,其中包含具有字段值的属性(您可能可以从示例中看出这一点)。

编辑:

我找到了解决方案,看我的答案,它简单而优雅。

最佳答案

我想通了,事实证明这是一个非常简单的解决方案,只需几个周期并在写入行和单元格之前预填充一个数组。

我测试了它,效果很好。 ;) 它可能对某些人有用,所以在这里:

foreach($records as $key => $row) {
foreach($row as $field => $value) {
$recNew[$field][] = $value;
}
}
//This creates a new array composed/transposed with the field names as keys and
//the "rowed" values as sub-arrays.

echo "<table>\n";

foreach ($recNew as $key => $values) // For every field name (id, name, last_name, gender)
{
echo "<tr>\n"; // start the row
echo "\t<td>" . $key . "</td>\n" ; // create a table cell with the field name
foreach ($values as $cell) // for every sub-array iterate through all values
{
echo "\t<td>" . $cell . "</td>\n"; // write cells next to each other
}
echo "</tr>\n"; // end row

}

echo "</table>";

关于php - Foreach 行显示为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8904731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com