问题描述
嘿伙计们,我似乎无法正确理解这里的语法,我只是想看看类型是否存在,我试过了
Hey guys I can't seem to get the syntax here right, I'm just trying to see if type exists,I've tried
if($obj->type) /* do something */
if($obj[0]->type) /* do something */
if($obj->type[0]) /* do something */
关于这个
stdClass::__set_state(
array(
'0' =>
stdClass::__set_state(
array(
'report_number' => '555',
'type' => 'citrus',
'region' => 'Seattle',
'customer_number' => '9757',
'customer' => 'The Name',
'location' => 'West Seattle, WA',
'shipper' => 'Yamato Transport',
'po' => '33215',
'commodity' => 'RARE',
'label' => 'PRODUCE',
)),
))
但似乎无法做到正确,我相信这与[0] 是 int 而不是 varchar 但我不知道....
But just can't seem to get it right, I believe it has something to do with[0] being an int instead of varchar but I have no idea....
推荐答案
您问题中的输出是由 var_export
创建的,它将对象的数据表示为 array
.但不要被误导,它实际上是一个对象.
The output in your question is created by var_export
which represents the data of the object as an array
. But don't get mislead by that, it's in fact an object.
通过以下语法访问对象属性:
Object properties are accessed by this syntax:
$obj->property
在您的情况下,属性名为 0
,这对于 PHP 来说很难用纯代码处理,因为它不是您可以像这样立即编写的属性名称:
In your case the property is named 0
which is hard for PHP to deal with in plain code as it's not a property name you could write right away like this:
$obj->0
相反,您需要通过将其包含在 {}
中来告诉 PHP 解析器名称是什么:
Instead, you need to tell the PHP parser what the name is by enclosing it into {}
:
$obj->{0}
然后您可以进一步遍历以访问 0
的 type
属性:
You can then traverse further on to access the type
property of 0
:
$obj->{0}->type
希望这有帮助,问题不时出现,这是一个相关的,有更多相关链接:如何访问此对象属性?.
Hope this is helpful, the question comes up from time to time, this is a related one with more related links: How do I access this object property?.
PHP 手册对此有记录,但在 上不是很明显变量变量入口:
The PHP Manual has this documented, but not very obvious on the Variable variables entry:
为了在数组中使用可变变量,您必须解决歧义问题.也就是说,如果您编写 $$a[1]
那么解析器需要知道您是否打算使用 $a[1]
作为变量,或者您是否想要$$a
作为变量,然后是来自该变量的 [1]
索引.解决这种歧义的语法是:${$a[1]}
用于第一种情况,${$a}[1]
用于第二种情况.
这篇关于访问嵌套对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!