Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 值为空时,json_decode返回null_Php_Php 5.3_Json - Fatal编程技术网

Php 值为空时,json_decode返回null

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"

例如,我在尝试将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.', "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
}