json_decode to array

前端 未结 12 1342
野的像风
野的像风 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条回答
  • 2020-11-22 01:48

    This will also change it into an array:

    <?php
        print_r((array) json_decode($object));
    ?>
    
    0 讨论(0)
  • 2020-11-22 01:51

    This is a late contribution, but there is a valid case for casting json_decode with (array).
    Consider the following:

    $jsondata = '';
    $arr = json_decode($jsondata, true);
    foreach ($arr as $k=>$v){
        echo $v; // etc.
    }
    

    If $jsondata is ever returned as an empty string (as in my experience it often is), json_decode will return NULL, resulting in the error Warning: Invalid argument supplied for foreach() on line 3. You could add a line of if/then code or a ternary operator, but IMO it's cleaner to simply change line 2 to ...

    $arr = (array) json_decode($jsondata,true);
    

    ... unless you are json_decodeing millions of large arrays at once, in which case as @TCB13 points out, performance could be negatively effected.

    0 讨论(0)
  • Please try this

    <?php
    $json_string = 'http://www.domain.com/jsondata.json';
    
    $jsondata = file_get_contents($json_string);
    $obj = json_decode($jsondata, true);
    echo "<pre>"; print_r($obj['Result']);
    ?>
    
    0 讨论(0)
  • 2020-11-22 01:57

    Try like this:

    $json_string = 'https://example.com/jsondata.json';
    $jsondata = file_get_contents($json_string);
    $obj = json_decode($jsondata);
    print_r($obj->Result);
    foreach($obj->Result as $value){
      echo $value->id; //change accordingly
    }
    
    0 讨论(0)
  • 2020-11-22 01:58

    As per the documentation, you need to specify if you want an associative array instead of an object from json_decode, this would be the code:

    json_decode($jsondata, true);
    
    0 讨论(0)
  • 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)
    }
    
    0 讨论(0)
提交回复
热议问题