简体   繁体   English

如何在php中访问复杂对象

[英]how to access complex object in php

I have the following data structure $all =我有以下数据结构 $all =

[0] => stdClass Object
    (
        [abc@gmail.com] => Array
            (
                [usr] => 130
                [fname] => Bob
                [lname] => thekid
                [email] => abc@gmail.com
                [news] => 0
                [wres] => 1
                [SWAGLeaders] => 0
                [cca-cpg] => 1
                [cleanup-cpg] => 0
                [gas-cpg] => 1
                [pollinators-cpg] => 0
                [climate-int] => 0
                [composting-int] => 0
                [energy-int] => 1
                [other-int] => 0
                [pollinators-int] => 0
                [recycling-int] => 0
                [transport-int] => 1
                [trees-int] => 0
                [water-int] => 0
            )

    )

How do I access the inner keys/values?如何访问内部键/值?

I tried print_r($all[0]['abc@gmail.com']);我试过print_r($all[0]['abc@gmail.com']); but that produced nothing但这没有产生任何结果

also, is 'abc@gmail.com' a key?另外,“abc@gmail.com”是钥匙吗? or a variable?还是变量? I thought it was a key whose value is the array and then inside the array we have additional key/value pairs我认为这是一个键,其值为数组,然后在数组内部我们有额外的键/值对

That is clearly an object (denoted by the stdClass Object in that output), not an array.这显然是一个对象(由该输出中的stdClass Object表示),而不是一个数组。 You can access it with $all->{"abc@gmail.com"} .您可以使用$all->{"abc@gmail.com"}访问它。 This is how you force complex interpolation in place of a PHP symbol, where the symbol violates PHP's naming rules.这就是强制复杂插值代替 PHP 符号的方式,其中符号违反了 PHP 的命名规则。 So for example, object properties with dashes, or other illegal symbols, in them can be forced to be evaluated as strings and then as property names by wrapping them in strings and then in braces: $obj->{"this-is-ok"} whereas $obj->this-is-not .因此,例如,可以强制将带有破折号或其他非法符号的对象属性评估为字符串,然后通过将它们包装在字符串中然后用大括号将它们包装为属性名称: $obj->{"this-is-ok"}$obj->this-is-not

As a side note, if this object comes from JSON, you can always force it to be stored as an array by utilizing the second argument of json_decode() , which if set to true will force the object to be built as an array instead.附带说明一下,如果此对象来自 JSON,您始终可以通过使用json_decode()的第二个参数强制将其存储为数组,如果设置为true则会强制将对象构建为数组。 For some people this may make the dereferencing of keys easier.对于某些人来说,这可能会使取消引用密钥更容易。 So if $all["abc@gmail.com"] seems more natural to you than $all->{"abc@gmail.com"} that might be the better approach.因此,如果$all["abc@gmail.com"]对您来说似乎比$all->{"abc@gmail.com"}更自然,那可能是更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM