【问题标题】:PHP - json encode/decode process convert associative array to objectPHP - json 编码/解码过程将关联数组转换为对象
【发布时间】: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


【解决方案1】:

你试过json_decode($test, true)吗?

【讨论】:

    【解决方案2】:

    您可以设置第二个参数。当 TRUE 时,返回的对象将被转换为关联数组。 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));
    
    ?>
    

    输出:

    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)
    }
    

    【讨论】:

    • 那么嵌套呢?
    【解决方案3】:

    是的,我已经用过了...

    如果我使用 json_decode($test, true) 适用于关联数组但不适用于对象,因为原始对象将被解码为数组...

    所以问题是我必须将解码的变量作为原始变量(对于这两种情况)。

    我对变量进行编码,然后存储在一个文件中,然后解码,我必须以与访问原始变量相同的方式访问它们,所以如果原始变量是关联数组,我必须将其作为关联数组x["field"] 访问,如果原始变量是一个对象我必须作为对象访问 x-&gt;field

    序列化完成这项工作,json 不,那是我关心的......也许 json 不是为了这个目的而考虑的?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      • 2011-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多