Possible Duplicate:
Iterating through stdClass obj’s that are contained within a parent stdClass Obj. (aka: iterating through child objects)
…bccause if the parent object is empty foreach shows an error. for() would be my preferred loop logic but I do not know how to access the child objects properties.
Work-ish code:
foreach ($main_object as $object) {
$object->value = $object->value * 3.14;
}
BUT when $main_object is empty or null, foreach dumps out an error.
I’m looking for something more like this:
(pseudo) code:
for ($p = 0; $p < counter($main_object); $p++) {
//$p being the index'd id of the child object. That is where I'm having issues, how do I refer to child X within a parent object.
$main_object->$p->value = $main_object->$p->value * 3.14;
}
Now if ‘$main_object’ is empty/null no error is thrown, logic keeps on truckin’.
How do I access child object $x->properties when object is one of a group of child objects inside a parent object?
Just check first that the object contains at least one item before iterating:
I too find this annoying, but
foreachis extremely easy to work with so it’s a bit of a tradeoff. I’d still rather do the above than use something likefor(which could also work).PHP count docs
Cheers