当值为空时,json_decode返回null

时间:2012-03-28 17:54:58

标签: php php-5.3 json

我在尝试将decode 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

我怎样才能返回这样的结果?

1 个答案:

答案 0 :(得分: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
}
相关问题