php - 当数组中的数字等于零时显示其他内容

标签 php mysql


我设法显示了 MySQL 数据库中的数据,但遇到了问题。
我想要实现的是,当 price 的值等于 0 时,它应该显示 Free 而不是仅显示 0。
我试图在网上找到解决方案,但也许我搜索错了,因为我对 PHP 还很陌生。

<?php
while ($row = mysqli_fetch_array($query))
{
    $amount  = $row['amount'] == 0 ? '' : number_format($row['amount']);
    echo '
        echo '<tr>
                <td>'.$row['id'].'</td>
                <td>'.$row['event'].'</td>
                <td>'.$row['price'].'</td>
                <td>'.$row['address'].'</td>
                <td>'.$row['info'].'</td>
                <td>'.$row['contact'].'</td>
            </tr>';
}?>

最佳答案

你很接近。看起来您正在测试三元中的 0 并为 $amount

赋值或不赋值
$amount = ($row['amount'] == 0) ? '' : number_format($row['amount']);

您可以将其更改为(假设 amount 数据类型是数字而不是字符串):

$amount = ($row['amount']) ? '$'.number_format($row['amount']) : 'Free';

如果 amount 是数据库中的一个字符串,您可能需要测试 "0" 就像您几乎:

$amount = ($row['amount'] !== "0") ? '$'.number_format($row['amount']) : 'Free';

那么你有下一个问题 - 你从未在你的代码中使用过 $amount :]

完整更改(基于您的代码示例):

<?php
    while ($row = mysqli_fetch_array($query)) {
        // Assign either 'Free' or a formatted value to '$amount'
        $amount = ($row['amount']) ? '$'.number_format($row['amount']) : 'Free';
        // And be sure to use $amount here
        echo '<tr>
            <td>'.$row['id'].'</td>
            <td>'.$row['event'].'</td>
            <td>'.$amount.'</td>
            <td>'.$row['adress'].'</td>
            <td>'.$row['info'].'</td>
            <td>'.$row['contact'].'</td>
        </tr>';
    }
?>

注意:您在 $row['address'] 中也有拼写错误,除非错误也出现在 DB 表中,否则它应该是 $row['address' ]

关于php - 当数组中的数字等于零时显示其他内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48483118/

相关文章:

PHP - 类构造中的 Require_once

java - 如何下载从数据库中获取结果集的excel表

mysql - 在单个 SQL 中更新具有不同值的多行

mysql - VB.Net 使用唯一键更新 MySQL

javascript - PHP AJAX 脚本无法在所有条件下正常工作

php - 多语言应用程序: store/read translation

PHP 比较数据库中的值

当我更改表时,MySQL Workbench 不显示列

WHERE 条件下的 MySql 存储过程错误

PHP proc_open 阻止读取 stdout,直到 C 程序终止