首页 > 解决方案 > 我将如何编写我的条件来确定数据是狗还是猫,并且能够在其各自的列下显示它?

问题描述

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;
    }
}
?>

标签: php

解决方案


这是一种可能性。当它是一只狗时,它为猫添加一个空单元格,当它是一只猫时,它为狗添加一个空单元格。

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;

推荐阅读