How to iterate over an array of stdObject elements

2019-08-28 09:57发布

问题:

This is the print_r() version of a data structure that I need to access via a foreach loop:

stdClass Object
(
    [DetailedResponse] => Array
        (
            [0] => stdClass Object
                ( ...
                )

            [1] => stdClass Object
                ( 
...

Now, how do I iterate though these objects?

I can sense that I should be doing something like this:

$object->DetailedResponse[0];
$object->DetailedResponse[1];

But how do I put it in a foreach type loop!!

回答1:

seems like there are multiple objects in that obj.. you might need to do more foreach loops.. this code should get you the first sessionId in that obj.

foreach ($detailedresponses as $detailedresponse) {
    foreach ($detailedresponseas as $response) {
        echo $response->sessionId;

    }
}

run this code to see the obj in a clearer way:
echo '<pre>'; print_r($detailsresponses); exit;

replace '$detailedresponses' with your correct variable name and post it back here, it should make things easier to read.

EDIT
check out this URL, I put my test data in there: http://pastie.org/1130373

I recreated the object you're getting and put comments in there so you can understand what's happening :)

AND, you can get the properties like this:

echo $object->DetailedResponse[0]->sessionId;


回答2:

very simple. you have a so called standard-object of php. it's accessable like any other object in php by the $object->property syntax

so you can iterate over it this way: foreach($object as $property), or foreach($object as $prop_name => $prop_val) where you can access the properties by $object->$prop_name.



回答3:

If you want to save a class, for re-using it later, you'd better to use serialize and unserialize()



回答4:

Got a good solution to this - had a stdClass that contained other stdClases and arrays

function cleanEveryElement($someStdClass) {
    foreach ($someStdClass as &$property) {        
        if ($property instanceof stdClass || is_array($property)) {
            $property = cleanEveryElement($property);
        }
    else {
        // Perform some function on each element, eg:
        $property = trim($property);
        }
    }
return $someStdClass;
}