【发布时间】:2015-09-20 05:50:16
【问题描述】:
我需要将 php 变量存储到文件中,因此我决定对它们进行序列化或 jsonize(可能是 jsonify XD)。
出于便携性目的,我更喜欢 json 解决方案...
在测试期间,我注意到关联数组被 json 解码为对象,我不能将它用作关联数组,但我必须用作对象。
非关联数组被正确解码为非关联数组..
我做错了吗?
或者这只是 php json 函数的正常行为
这里是示例代码
$test = array("test1" => 1, "test2" => 2);
$json = json_decode(json_encode($test));
$serialize = unserialize(serialize($test));
//output -> stdClass::__set_state(array( 'test1' => 1, 'test2' => 2, ))
// cant access to $json["test1"] as in $test but $json->test why?????
var_export($json);
//ouptut -> array ( 'test1' => 1, 'test2' => 2, )
//here i can $serialize["test1"]
var_export($serialize);
【问题讨论】:
-
只要使用
json_decode(json_encode($test), true);,你会得到一个数组而不是一个对象。
标签: php json serialization associative-array