我设法显示了 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/