PHP/JSON - stdClass Object

前端 未结 2 1809
天涯浪人
天涯浪人 2020-12-09 00:05

I\'m pretty new to arrays still. I need some help - I have some JSON, and I\'ve run it through some PHP that basically parses the JSON and decodes it as follows:

         


        
相关标签:
2条回答
  • 2020-12-09 00:29

    You can use get_object_vars() to get an array of the object's properties, or call json_decode() with json_decode($string,true); to get an associative array.


    Example:

    <?php
    $foo = array('123456' =>
     array('bar' =>
            array('foo'=>1,'bar'=>2)));
    
    
    //as object
    var_dump($opt1 = json_decode(json_encode($foo)));
    
    echo $opt1->{'123456'}->bar->foo;
    
    foreach(get_object_vars($opt1->{'123456'}->bar) as $key => $value){
        echo $key.':'.$value.PHP_EOL;
    }
    
    //as array
    var_dump($opt2 = json_decode(json_encode($foo),true));
    
    echo $opt2['123456']['bar']['foo'];
    
    foreach($opt2['123456']['bar'] as $key => $value){
        echo $key.':'.$value.PHP_EOL;
    }
    ?>
    

    Output:

    object(stdClass)#1 (1) {
      ["123456"]=>
      object(stdClass)#2 (1) {
        ["bar"]=>
        object(stdClass)#3 (2) {
          ["foo"]=>
          int(1)
          ["bar"]=>
          int(2)
        }
      }
    }
    1
    foo:1
    bar:2
    
    array(1) {
      [123456]=>
      array(1) {
        ["bar"]=>
        array(2) {
          ["foo"]=>
          int(1)
          ["bar"]=>
          int(2)
        }
      }
    }
    1
    foo:1
    bar:2
    
    0 讨论(0)
  • 2020-12-09 00:29

    You can iterate on the stdClass with foreach.

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