Php 如何访问对象的数字属性
我有一个目标:Php 如何访问对象的数字属性,php,Php,我有一个目标: stdClass Object ( [0] => stdClass Object ( [type] => A [quantity] => 30 ) [1] => stdClass Object ( [type] => P [quantity] => 129 ) ) 但是,我无法访问子对象(例如,$Data->0->qua
stdClass Object (
[0] => stdClass Object (
[type] => A
[quantity] => 30
)
[1] => stdClass Object (
[type] => P
[quantity] => 129
)
)
但是,我无法访问子对象(例如,$Data->0->quantity
),因为在PHP中无法访问对象的数字属性
如何在不使用循环的情况下访问子对象?为此使用循环。(如果我没弄错你的问题…就像任何带有公共变量的对象一样:
$oStdClass->0->quantity = 10;
或者通过它们来循环
foreach($oStdClasses as $oStdClass) {
$oStdClass->quantity = 10;
}
对象的方法和/或属性可通过箭头
->
操作符访问。因此,要访问数量,您需要执行以下操作:
$quantity = $object->quantity;
也许吧
这似乎有点奇怪——对象通常不应该具有无效PHP变量名的属性——但仍然可以访问其中的所有变量 使用get\u object\u vars
// The following code doubles all of the "quantity" properties of
// all of the sub-objects.
foreach( get_object_vars( $strangObject ) as $key => $value )
{
// in here, $key will be your (numeric) property name of the outer object
// and $value will be the object stored at that property.
$value->quantity *= 2;
}
这是一篇有趣的文章。使用变量解决以下问题:
print_r($item->0);
但这是可行的:
$index = 0;
print_r($item->$index);
不,它不起作用。这已经是问题所在了。我试过这样的代码:
echo$this->Data->0->type代码>并且它给出了语法错误。我不确定你是如何得到整数成员的,但是foreach循环应该可以工作。
$index = 0;
print_r($item->$index);