【问题标题】:PHP/JSON - stdClass ObjectPHP/JSON - 标准类对象
【发布时间】:2011-04-14 20:11:44
【问题描述】:

我对数组还是很陌生。我需要一些帮助 - 我有一些 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 等)。我该怎么办?

【问题讨论】:

    标签: php arrays json iteration


    【解决方案1】:

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


    示例:

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

    【讨论】:

    • 我已经完成了json_decode($string,true);,但是,我遇到了称为数组引用的数字的问题。例如,号码是 2010091907,但是当我发出 foreach ($json-&gt;2010091907 as $game) 时,我收到错误 Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE
    • 使用 $json-&gt;{'2010091907'} 作为“非法”变量名。
    • 快到了:foreach ($json-&gt;{'2010091907'} as $game),我得到了错误:Warning: Invalid argument supplied for foreach()。参考我上面的 JSON 到 ARRAY 的输出。我需要能够调用数据,这些似乎是递归数组(不确定正式名称是什么)。
    • 您刚刚尝试过json_decode($string,true); 路由吗?简单得多,然后继续将它们转换为数组......
    • 我不确定我是否遵循 - 我正在通过 URL 接收 JSON。然后我将整个 JSON 输出放入一个数组中(通过json_decode($data,true);。从那里,我想遍历数组内容并从数组中调用某些数据。你能否提供一些代码,就像我正在做的那样这一切都错了。
    【解决方案2】:

    您可以使用foreach 迭代stdClass

    【讨论】:

    • 该死,你是对的。为什么 PHP 人没有礼貌地让stdClass instanceof Traversable 成为真的我想知道....
    猜你喜欢
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多