Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/253.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何访问对象的数字属性_Php - Fatal编程技术网

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);