iterating through a stdClass object in PHP
Since this is the top result in Google if you search for iterate over stdclass
it may be helpful to answer the question in the title:
You can iterate overa stdclass simply by using foreach:
$user = new \stdClass();
$user->flag = 'red';
foreach ($user as $key => $value) {
// $key is `flag`
// $value is `red`
}
I know it's an old post , but for sake of others: when working with stdClass you should use Reflections:
$obj = new ReflectionObject($object);
$propeties = $obj->getProperties();
foreach($properties as $property) {
$name = $property->getName(); <-- this is the reflection class
$value = $object->$name; <--- $object is your original $object
here you need to handle the result (store in array etc)
}
echo "<table>"
foreach ($object->values as $arr) {
foreach ($arr as $obj) {
$id = $obj->group->id;
$name = $obj->group->name;
$html = "<tr>";
$html .= "<td>Name : $name</td>";
$html .= "<td>Id : $id</td>";
$html .= "</tr>";
}
}
echo "</table>";
function objectToArray( $data )
{
if ( is_object( $data ) )
$d = get_object_vars( $data );
}
Convert the Object to array first like:
$results = objectToArray( $results );
and use
foreach( $results as result ){... ...}