简体   繁体   中英

How to iterate over an array of stdObject elements in PHP?

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!!

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;

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;
}

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 .

如果要保存一个类,以便以后再使用,则最好使用serializeunserialize()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM