Getting an array result from json_decode

前端 未结 5 1060
逝去的感伤
逝去的感伤 2020-12-20 17:24

How do I get an array as a result from json_decode()?

I had an array like this:

$array = array(
  \'mod_status\' => \'yes\',
  \'mod_         


        
相关标签:
5条回答
  • 2020-12-20 17:30
    $decode = json_decode($dbresult, true);
    

    Or

    $decode = (array)json_decode($dbresult);
    
    0 讨论(0)
  • 2020-12-20 17:33

    Set the second parameter of json_decode to true to force associative arrays:

    $decode = json_decode($dbresult, true);
    
    0 讨论(0)
  • 2020-12-20 17:34

    Casting the object result of json_decode to an array can have unexpected results (and cause headaches). Because of this, it is recommended to use json_decode($json, true) instead of (array)json_decode($json). Here is an example:

    Broken:

    <?php
    
    $json = '{"14":"29","15":"30"}';
    $data = json_decode($json);
    $data = (array)$data;
    
    // Array ( [14] => 29 [15] => 30 )
    print_r($data);
    
    // Array ( [0] => 14 [1] => 15 )
    print_r(array_keys($data));
    
    // all of these fail
    echo $data["14"];
    echo $data[14];
    echo $data['14'];
    
    // this also fails
    foreach(array_keys($data) as $key) {
        echo $data[$key];
    }
    

    Working:

    <?php
    
    $json = '{"14":"29","15":"30"}';
    $data = json_decode($json, true);
    
    // Array ( [14] => 29 [15] => 30 )
    print_r($data);
    
    // Array ( [0] => 14 [1] => 15 )
    print_r(array_keys($data));
    
    // all of these work
    echo $data["14"];
    echo $data[14];
    echo $data['14'];
    
    // this also works
    foreach(array_keys($data) as $key) {
        echo $data[$key];
    }
    
    0 讨论(0)
  • 2020-12-20 17:44

    As per http://in3.php.net/json_decode:

    $decode = json_decode($dbresult, TRUE);
    
    0 讨论(0)
  • 2020-12-20 17:55

    If you only use that data in PHP I recommend using serialize and unserialize instead or else you'll never be able to differentiate between objects and associative arrays, because the object class information is lost when encoding to JSON.

    <?php
    class myClass{// this information will be lost when JSON encoding //
        public function myMethod(){
            echo 'Hello there!';
        }
    }
    $x = array('a'=>1, 'b'=>2);
    $y = new myClass;
    $y->a = 1;
    $y->b = 2;
    echo json_encode($x), "\n", json_encode($y); // identical
    echo "\n", serialize($x), "\n", serialize($y); // not identical
    ?>
    

    Run it.

    0 讨论(0)
提交回复
热议问题