代码之家  ›  专栏  ›  技术社区  ›  drewrockshard

php/json-stdclass对象

  •  10
  • drewrockshard  · 技术社区  · 14 年前

    我还是数组新手。我需要一些帮助-我有一些JSON,我已经通过一些PHP运行它,基本上解析JSON并按如下方式对其进行解码:

    stdClass Object
    (
        [2010091907] => stdClass Object
            (
            [home] => stdClass Object
                (
                    [score] => stdClass Object
                        (
                            [1] => 7
                            [2] => 17
                            [3] => 10
                            [4] => 7
                            [5] => 0
                            [T] => 41
                        )
    
                    [abbr] => ATL
                    [to] => 2
                )
    

    事实上,这种情况不断发生,但我的问题是 stdClass Object 部分。我需要能够在for循环中调用它,然后遍历每个部分(home、score、abbr、to等)。我该怎么办?

    2 回复  |  直到 14 年前
        1
  •  21
  •   Wrikken    14 年前

    你可以使用 get_object_vars() 获取对象属性的数组,或调用 json_decode() 具有 json_decode($string,true); 获取关联数组。


    例子:

    <?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;
    }
    ?>
    

    输出:

    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
    
        2
  •  2
  •   tamasd    14 年前

    您可以迭代 stdClass 具有 foreach .