如何防止json的空值?

时间:2015-08-27 11:59:03

标签: php json

在数组中存储动态值,并使用json_encode转换json,转换后打印json值,但是某些值返回null值,但是打印数组值,它显示正确,我该怎么办,请帮帮我。 / p>

我的编码如下,

header('Content-type: application/json');
$return=array();
$level=$_REQUEST['level'];
$sql="SELECT * FROM guess WHERE level=$level";
$res = $st->query($sql);
if($res->num_rows>=1){
    $images=array();
    while($row= $res->fetch_assoc())
    {
        $images[]=$row;
    }
    $return['list']=$images;
}
echo json_encode($return);

我在json中的输出,

{"list":[{"id":"1","type":"text","question":null,"answer":"feed"}]

在数组中,

[list] => Array
    (
        [0] => Array
            (
                [id] => 1
                [type] => text
                [question] => WHAT CHARITY Christian organization committed to feeding God’s children hungry in body and spirit?
                [answer] => feed
            )


    )

2 个答案:

答案 0 :(得分:0)

json_encode要求数据中的字符串编码为UTF-8。

updateProductsQuery = "
    UPDATE hashtable AS h
    JOIN p ON h.id = p.id
    LEFT JOIN att1 on p.id = att1.attid and att1.attrkey = 'PARAM'
    LEFT JOIN att2 on p.id = att2.attid and att2.attrkey = 'NODE' 
    LEFT JOIN u on p.id = u.umid and u.lang = 'EN'
    SET h.hash = MD5(CONCAT_WS('.', p.desc, p.macode, p.manuf, u.unit, p.weight, p.number, att1.attr, p.vcode, att2.attr))
    LIMIT " + str(limit1) + ", " + str(limit2)

答案 1 :(得分:0)

使用mysql IFNULL函数并修改你的sql查询 - 所以你不必编写额外的php代码,因为如果第一个参数(问题列)ifnull函数返回第二个参数(你想要的字符串)值value为null

SELECT col1, col2, IFNULL(question, 'WHAT CHARITY Christian organization committed to feeding God\’s children hungry in body and spirit?') as question  FROM guess WHERE level=$level

for more about ifnull function - click to read