引用动态关联数组位置 [英] Referencing a dynamic associative array position

查看:80
本文介绍了引用动态关联数组位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从在线来源请求数据,然后将其解码为json StdClass对象(使用php).完成此操作后,我将得到以下内容(请参见下文).我正在尝试通过执行echo $response->stuff->WHAT GOES HERE?->otherstuff

I'm requesting data from an online source which I then decode into json StdClass objects (using php). Once I've done this I have the following (see below). I'm trying to extract the elements in 'otherstuff' by doing echo $response->stuff->WHAT GOES HERE?->otherstuff

但是我无法对[2010-12]进行硬编码,因为它是一个日期,有什么方法可以打电话给我,例如$response->stuff->nextsibling->stuff

However I cant hard code the [2010-12] because its a date, is there any way I can call e.g. $response->stuff->nextsibling->stuff

我希望这对某人有意义:D当前,我正在使用$key => $value进行循环操作,并提取键值并在我的$response->stuff->$key->stuff调用中使用它.

I hope this makes sense to someone :D Currently i'm bastardising this with a $key => $value for loop and extracting the key value and using it in my $response->stuff->$key->stuff call.

stdClass Object
(
    [commentary] => 
    [stuff] => stdClass Object
        (
            **[2010-12]** => stdClass Object
                (
                    [otherstuff] => stdClass Object
                        (
                            [otherstuffrate] => 1
                            [otherstufflevel] => 1
                            [otherstufftotal] => 1
                        )    
                )

        )

) 

推荐答案

StdClass实例可以与某些数组函数,其中

StdClass instances can be used with some Array Functions, among them

  • current — Return the current element in an array and
  • key — Fetch a key from an array

您可以这样做(键盘)

$obj = new StdClass;
$obj->{"2012-10"} = 'foo';
echo current($obj); // foo
echo key($obj); // 2012-10

在旁注中,对象属性不应以数字开头,并且它们可能不包含破折号,因此,将TRUE作为第二个参数传递给json_decode,而不是使用StdClass对象.然后,返回的对象将转换为关联数组.

On a sidenote, object properties should not start with a number and they may not contain dashes, so instead of working with StdClass objects, pass in TRUE as the second argument to json_decode. Returned objects will be converted into associative arrays then.

这篇关于引用动态关联数组位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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