1

I have this object:

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

However, I cannot access the sub-objects (e.g., $Data->0->quantity) because numeric properties of objects are not accessible in PHP.

How can I access the sub-objects without resorting to looping?

kuzey beytar
  • 3,076
  • 6
  • 37
  • 46

6 Answers6

1

Just as any object with public variables:

$oStdClass->0->quantity = 10;

Or loop trough them.

foreach($oStdClasses as $oStdClass) {
     $oStdClass->quantity = 10;
}
Wesley van Opdorp
  • 14,888
  • 4
  • 41
  • 59
1

This seems a bit of a strange corner case -- objects generally are not supposed to have properties which aren't valid PHP variable names -- but it should still be possible to get to all of the variables there.

Use 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;
}
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
0

This is an interesting piece. Use variables to address:

print_r($item->0);

But this works:

$index = 0;
print_r($item->$index);
tika
  • 7,135
  • 3
  • 51
  • 82
0

Use a for-each loop for that. (If I understand your question right...)

Tobias
  • 7,238
  • 10
  • 46
  • 77
0

Object's methods and/or properties are accessed via the arrow -> operator. So to access quantity, you'd do:

$quantity = $object->quantity;
Carlos Campderrós
  • 22,354
  • 11
  • 51
  • 57
0

Maybe?

foreach($class as $v) echo($v->quantity);
Danzan
  • 958
  • 5
  • 8