php - 我将如何编写我的条件来确定数据是狗还是猫,并且能够在其各自的列下显示它?
问题描述
Customer's Name | Dog | Cat
Glenn | 1 |
Mark | | 1
Jim | 2 | 3
如果它属于 Dog 列或 Cat,如何识别我的计数?
<?php
require_once 'DbConnect.php';
$db = new DbConnect;
$conn = $db->connect();
$stmt = $conn->prepare("SELECT Customers_Name,Type, Count(Qunatity) AS count FROM dbo.Pet");
$stmt->execute();
$count = 0;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<tr>';
echo '<td>"'.$row['Customers_Name'].'"</td>' . PHP_EOL;
if ($row['type'] == "Dog"){
echo '<td>' . $row['count']. '</td>' ;
}else {
echo '<td>' . $row['count']. '</td>' . PHP_EOL;
}
}
?>
解决方案
这是一种可能性。当它是一只狗时,它为猫添加一个空单元格,当它是一只猫时,它为狗添加一个空单元格。
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<tr>';
echo '<td>'.$row['Customers_Name'].'</td>';
if ($row['type'] == "Dog") {
echo '<td>' . $row['count']. '</td><td></td>';
} else {
echo '<td></td><td>' . $row['count']. '</td>';
}
echo '</tr>' . PHP_EOL;
}
这是另一种选择,使用稍微不同的逻辑,以及创建 HTML 的不同方式。我个人觉得这更易读,而且如果你以后决定添加鸟、兔子等,它更容易扩展。
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)):
?>
<tr>
<td><?= $row['Customers_Name'] ?></td>
<td><?= $row['Type'] == 'Dog' ? $row['count'] : '' ?></td>
<td><?= $row['Type'] == 'Cat' ? $row['count'] : '' ?></td>
</tr>
<?php
endwhile;
请注意,如果您的客户同时拥有狗和猫(正如您所需的输出似乎表明的那样),那么这些都不够,您需要做更多的工作来将多行结果合并到一个表行中.
这是一个版本(未经测试),它将所有具有相同名称的行组合在一起,然后一次全部输出。如果您有大量数据,这将不是一个好方法,您最好更改数据库结构,或者至少按名称对查询进行排序并调整它以在获得时输出一行不同的名字。
$rows = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)):
if (!array_key_exists($row['Customers_Name'], $rows)) {
$rows[ $row['Customers_Name'] ] = [];
}
$rows[ $row['Customers_Name'] ][ $row['Type'] ] = $row['count'];
}
foreach ($rows as $name => $counts):
?>
<tr>
<td><?= $name ?></td>
<td><?= $counts['Dog'] ?? '' ?></td>
<td><?= $counts['Cat'] ?? '' ?></td>
</tr>
<?php
endforeach;
推荐阅读
- graph - 图 SDK 中的分页支持
- python-3.x - 无法使用 xml.etree.ElementTree 解析 html
- python - 如何只让超级用户编辑模型
- sql - 如何删除雪花中的所有 html 字符,不想在查询中包含所有 html 特殊字符(无硬编码)
- ruby-on-rails - 有没有办法通过在 Rails 中使用 Fast JSON API 来选择外部对象的一个属性?
- kubernetes - 在 POD 处于 RUNNING 状态后,kubernetes 事件中是否准备好探测?
- bash - 将 shell 脚本可选参数保存到外部文件
- sql - 需要两个表的 Oracle 查询连接
- react-native - 我正在尝试创建 bar 应用程序的启动画面,但我遇到了这种错误,请告诉我如何在 react-native 中修复这种错误
- docker - 有没有办法通过任务定义配置来轮换 AWS ECS 中的日志?