我正在从数据库中获取值并将其转换为json对象。它工作正常,但问题是如果值为空(未分配'null'值),它在json输出中显示为null。我试过条件检查它,如果值为空,则跳过它。但它没有用。我可以为if条件做什么,这样如果该值为空,则应跳过该值。请建议一些解决方案。我是php的新手
<?php
$connect = mysql_connect("localhost","plinlt","lajisdfla");
mysql_select_db("plinlt");
$result = mysql_query("SELECT field_id_6 FROM exp_channel_data") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["events"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
if($row["field_id_6"]==null)
{
Echo "";
}
else
{
$product["event"] = $row["field_id_6"];
// push single product into final response array
array_push($response["events"], $product);
}
}
// success
$response["success"] = 1;
$preserved = array_reverse($response, true);
// echoing JSON response
echo json_encode($preserved);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
答案 0 :(得分:2)
continue在循环结构中用于跳过当前循环迭代的其余部分,并在条件评估和下一次迭代开始时继续执行。
要检查空变量,更好的选项通常是empty()
PHP Manual: empty
所以,你可以使用这样的东西:
while ($row = mysql_fetch_array($result)) {
$product = array();
// if the field is blank, skip this row
if( empty($row["field_id_6"]) )
continue;
// it's not blank, do what we need
$product["event"] = $row["field_id_6"];
array_push($response["events"], $product);
}
答案 1 :(得分:0)
尝试if条件,
if($row["field_id_6"]==null || $row["field_id_6"] == "" || $row["field_id_6"] == " ")
{
//your code
}
答案 2 :(得分:0)
答案 3 :(得分:0)
而不是
if($row["field_id_6"]==null)
{
Echo "";
}
试
if($row["field_id_6"]==null || $row["field_id_6"]=="null" || empty($row["field_id_6"]) || trim($row["field_id_6"])=="")
{
continue;
}