gpt4 book ai didi

php 代码在 orderby 更改时创建新的 html 表

转载 作者:行者123 更新时间:2023-11-30 22:50:37 24 4
gpt4 key购买 nike

我有一个简单的脚本,它使用 sql 查询从数据库中获取数据并按特定列排序信息。正如您在下面的查询中看到的那样,每次“层级”发生变化时,我都希望能够创建一个新的 html 表。我怎样才能将其分解,以便该层显示在新的附加 HTML 表中?下面获取并显示信息,但无法区分层级。关于如何格式化这个的任何想法?

<?php
// You can place PHP like this

echo "<table class='table table-striped table-bordered table-hover table-condenced table-responsive'>";
echo "<tr><th>Channel</th><th>Description</th></tr>";

class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}

function current() {
return "<td>" . parent::current(). "</td>";
}

function beginChildren() {
echo "<tr>";
}

function endChildren() {
echo "</tr>" . "\n";
}
}

$servername = "localhost";
$username = "test";
$password = "pass";
$dbname = "Channel_Lineup";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT channel, description FROM Channel_LineUps WHERE Market_ID = 1 ORDER BY Tier ASC");
$stmt->execute();

// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";

?>

最佳答案

您的 SQL 语句没有返回层,因此很难打开它。

如果您更改返回层级的请求(将层级放在首位会使事情变得更简单):

$stmt = $conn->prepare("SELECT tier, channel, description FROM Channel_LineUps WHERE Market_ID = 1 ORDER BY Tier ASC");

然后你可以在 TableRows 类中添加一个 lastTier 值,如果当前层是和上次看到的不一样。您还可以更改 current() 函数以不输出“层”。

class TableRows extends RecursiveIteratorIterator {
private $lastTier = NULL;

function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}

function current() {
if (parent::key() != "tier") return "<td>" . parent::current(). "</td>";
}

function beginChildren() {
if ($this->lastTier != parent::current()) {
if (!is_null($this->lastTier)) echo "</table>\n";
echo "<table class='table table-striped table-bordered table-hover table-condenced table-responsive'>\n";
$this->lastTier = parent::current();
}
echo "<tr>";
}

function endChildren() {
echo "</tr>" . "\n";
}
}

关于php 代码在 orderby 更改时创建新的 html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28287437/

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