Php 值为空时,json_decode返回null
例如,我在尝试将json解码成数组时遇到了这个问题 这样很好用Php 值为空时,json_decode返回null,php,php-5.3,json,Php,Php 5.3,Json,例如,我在尝试将json解码成数组时遇到了这个问题 这样很好用 $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 = 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
那我怎么才能返回这样的结果呢?那是因为当你返回时
$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
}