PHP json_decode到关联数组

时间:2015-05-06 10:09:06

标签: php json

我刚刚在砖墙上砸了几个小时试图在PHP中使用json_decode()函数。 Stack Overflow 很多次出现了同样的问题,例如herehere

解决方法是as stated in the docs,如果你想从JSON对象获取一个关联数组,你需要在函数调用中包含第二个可选的true参数,如下所示: / p>

$assoc_array = json_decode($the_JSON,true);

另一方面,保留此参数会返回一个对象:

$php_objest = json_decode($the_JSON);

这对我来说最烦人,因为这是我在一段时间之前解决的问题,但是忘了。

是否有人同意将此默认设置为true而不是false反映了大多数用例?

编辑:根据下面的要求,导致此错误的用例(类似于我过去所做的)试图解码JSON对象,添加/重新排列一些值,然后重新编码。代码示例是:

$the_hardcoded_json_string = "{\"a\":60,\"vi\":0,\"is\":0}";
$the_associative_array = json_decode( $the_hardcoded_json_string, true );
$the_associative_array["c"] = 758;
$the_new_json_string = json_encode( $the_associative_array );

1 个答案:

答案 0 :(得分:1)

我不知道这是否适合讨论php的默认参数,但如果我想改变它,我会这样做:

function my_json_decode($json, $assoc=true, $depth=512, $options=0) {
    return json_decode($json, $assoc, $depth, $options);
} 

我希望我能正确理解你的问题。如果我不这样做,请纠正我。如果大多数用例需要将assoc-argument设置为true,那么我并不感到害羞。但是我担心如果他们现在将它改为true会有很多麻烦,因为需要重写很多代码。

相关问题