2012-03-28 118 views
2

当试图decode JSON为阵列,比如我碰到这个问题来了,json_decode返回NULL当值为空

它工作正常这个样子,

$year = 2012; 
$month = 3; 

$json = '{"year":'.$year.', "month":'.$month.'}'; 
$config = json_decode($json,true); 

var_dump($config); // return array. 

但如果我设置变量之一null,例如,

$year = 2012; 
$month = null; 

$json = '{"year":'.$year.', "month":'.$month.'}'; 
$config = json_decode($json,true); 

var_dump($config); // return null 

我这个结果后,

array 
    'year' => int 2012 
    'month' => null 

我该如何返回这样的结果呢?

回答

3

这是因为当你做

$json = '{"year":'.$year.', "month":'.$month.'}'; 

结果:

{"year":2012, "month":} 

这本身就不是一个有效的JSON,所以你得到NULL,如果你能帮助它做

$month = "null" 

我得到了以下代码:

$year = 2012; 
$month = "null"; 

$json = '{"year":'.$year.', "month":'.$month.'}'; 
echo $json . "\n"; 
$config = json_decode($json,true); 
var_dump($config); 

结果:

{"year":2012, "month":null} 
array(2) { 
    ["year"]=> 
    int(2012) 
    ["month"]=> 
    NULL 
} 
+0

得到它。感谢你的回答! – laukok 2012-03-28 18:13:55