json_decode to array

前端 未结 12 1353
野的像风
野的像风 2020-11-22 01:31

I am trying to decode a JSON string into an array but i get the following error.

Fatal error: Cannot use object of type stdClass as array in C:\\w

12条回答
  •  梦毁少年i
    2020-11-22 01:58

    According to the PHP Documentation json_decode function has a parameter named assoc which convert the returned objects into associative arrays

     mixed json_decode ( string $json [, bool $assoc = FALSE ] )
    

    Since assoc parameter is FALSE by default, You have to set this value to TRUE in order to retrieve an array.

    Examine the below code for an example implication:

    $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
    var_dump(json_decode($json));
    var_dump(json_decode($json, true));
    

    which outputs:

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

提交回复
热议问题