简体   繁体   English

PHP - json 编码/解码过程将关联数组转换为对象

[英]PHP - json encode/decode process convert associative array to object

i need to store php variables into files so i decide to serialize or jsonize (maybe jsonify XD) them.我需要将 php 变量存储到文件中,所以我决定序列化或 jsonize(也许 jsonify XD)它们。
For portability purpose i prefer json solution...出于便携性目的,我更喜欢 json 解决方案...
During test i notice associative array are json-decoded as object and i cant use it as associative array but i have to use as object.在测试期间,我注意到关联数组被 json 解码为对象,我不能将其用作关联数组,但我必须用作对象。
Non-associative array are json-decoded correctly as non-associative array..非关联数组被正确地 json 解码为非关联数组。
am i doing something wrong?难道我做错了什么?
or just this is a normal behavior of php json functions或者这只是 php json 函数的正常行为

here the example code这里是示例代码

$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($test, true)吗?

You can give set a second Parameter.您可以设置第二个参数。 When TRUE, returned objects will be converted into associative arrays.当为 TRUE 时,返回的对象将被转换为关联数组。 http://php.net/manual/en/function.json-decode.php http://php.net/manual/en/function.json-decode.php

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>

output:输出:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

yes i already use it...是的,我已经在用了...

if i use json_decode($test, true) works on associative array but wont work for object cause original object will be decoded as array...如果我使用json_decode($test, true)适用于关联数组,但json_decode($test, true)用于对象,因为原始对象将被解码为数组...

So the problem is i must have the decoded variables as the original variables (for both case).所以问题是我必须将解码的变量作为原始变量(对于这两种情况)。

I encode my variables then store in a file then decode and i must access them in the same way i access the original, so if the original was associative array i must access it as associative array x["field"] , if the original variables was a object i have to access as object x->field .我编码我的变量,然后存储在一个文件中,然后解码,我必须以访问原始变量的相同方式访问它们,所以如果原始变量是关联数组,我必须将它作为关联数组x["field"] ,如果原始变量是我必须作为对象x->field访问的对象。

Serialize do the job, json no, thats my concern... maybe json is not thought for that purpose?序列化完成这项工作,json 不,那是我关心的……也许 json 不是为此目的而考虑的?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM