我的SQL数据库中有可变类型的数据,我正在用PHP对一个表进行聚合。
有时我有3列,有时我有更多,这取决于数据的类型。如果我使用:
$fourthcolumn=$row['fourth'];
if(empty($fourthcolumn)){
// DO NOTHING
}else{
echo "<td class='fourth'>" . $fourthcolumn. "</td>";
}
然后,它按预期工作,但有一个例外:有些列是数量。当数量为"0"时,它将返回为空,并且不会生成值为"0"的td。
在我的结构中,如果没有信息,那么单元格是完全空白的,这就是我所期望的空
有什么方法可以返回"0"吗?我做错了什么?
empty(0)
在php 中评估为true
参见手动
这样你就可以明确地检查
if(empty($fourthcolumn) && $fourthcolumn !==0 && $fourthcolumn !== "0"){
// DO NOTHING
}else{
echo "<td class='fourth'>" . $fourthcolumn. "</td>";
}
http://php.net/manual/en/function.empty.php
0将被认为是错误的。
我建议使用
$fourthcolumn=$row['fourth'];
if(isset($fourthcolumn)){
echo "<td class='fourth'>" . $fourthcolumn. "</td>";
}else{
// DO NOTHING
}
isset检查变量是否为空。
http://php.net/manual/en/function.isset.php
bool空(混合$var)
确定变量是否为空。如果变量不存在或其值等于FALSE,则视为空。如果变量不存在,empty()不会生成警告。
在PHP中,0==false。因此,如果空(正确地)检查的值为0,则返回true。
问题可以通过以下方式解决:
if(empty($fourthcolumn) && $fourthcolumn !== 0 && $fourthcolumn !== "0"){
// DO NOTHING
}else{
在进行检查以确保$thurthcolumn不等于数字0或字符串"0"的情况下;0";(例如,使用严格相等,因此它不会匹配false或空字符串)。
使用这个
$fourthcolumn=$row['fourth'] ?: 0;
它像这样描述
如果$row['fourth']
为空,则0