【问题标题】:How to access numeric property of an object [duplicate]如何访问对象的数字属性[重复]
【发布时间】:2011-08-27 22:57:25
【问题描述】:

我有这个对象:

 stdClass Object ( 
    [0] => stdClass Object ( 
         [type] => A 
         [quantity] => 30 
    )
    [1] => stdClass Object ( 
         [type] => P 
         [quantity] => 129
    ) 
 ) 

但是,我无法访问子对象(例如,$Data->0->quantity),因为在 PHP 中无法访问对象的数字属性。

如何在不使用循环的情况下访问子对象?

【问题讨论】:

    标签: php


    【解决方案1】:

    这是一个有趣的作品。使用变量来解决:

    print_r($item->0);
    

    但这有效:

    $index = 0;
    print_r($item->$index);
    

    【讨论】:

      【解决方案2】:

      这似乎有点奇怪——对象通常不应该具有不是有效 PHP 变量名的属性——但仍然应该可以访问那里的所有变量。

      使用 get_object_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;
      }
      

      【讨论】:

        【解决方案3】:

        也许?

        foreach($class as $v) echo($v->quantity);
        

        【讨论】:

          【解决方案4】:

          对象的方法和/或属性通过箭头-> 操作符访问。所以要访问数量,你会这样做:

          $quantity = $object->quantity;
          

          【讨论】:

            【解决方案5】:

            就像任何带有公共变量的对象一样:

            $oStdClass->0->quantity = 10;
            

            或者通过它们循环。

            foreach($oStdClasses as $oStdClass) {
                 $oStdClass->quantity = 10;
            }
            

            【讨论】:

            • 不,它不起作用。这已经是问题所在了。我试过你的代码是这样的:echo $this->Data->0->type; 它给出了语法错误。
            • 我不太确定你是如何在其中获得整数成员的,但 foreach 循环仍然应该可以工作。
            【解决方案6】:

            为此使用for-each 循环。 (如果我理解你的问题的话......)

            【讨论】:

              猜你喜欢
              • 2018-10-18
              • 2019-02-04
              • 2012-09-29
              • 2012-08-03
              • 2012-06-30
              • 2020-08-09
              • 2017-05-26
              • 2019-01-31
              • 2013-12-07
              相关资源
              最近更新 更多