PHP/JSON - 标准类对象 [英] PHP/JSON - stdClass Object

查看:24
本文介绍了PHP/JSON - 标准类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对数组还是很陌生.我需要一些帮助 - 我有一些 JSON,我已经通过一些 PHP 运行它,基本上解析 JSON 并将其解码如下:

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:

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 等).我该怎么办?

This actually goes on and on - BUT - my problem is the stdClass Object part. I need to be able to call this in a for loop and then iterate through each section (home, score, abbr, to, etc). How would I go about this?

推荐答案

你可以使用 get_object_vars() 来获取对象属性的数组,或者调用 json_decode()json_decode($string,true); 得到一个关联数组.

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.

示例:

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

这篇关于PHP/JSON - 标准类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆