2012-03-28 117 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