How to iterate over an array of stdObject elements

2019-08-28 10:19发布

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

4条回答
再贱就再见
2楼-- · 2019-08-28 10:23

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

查看更多
闹够了就滚
3楼-- · 2019-08-28 10:24

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.

查看更多
地球回转人心会变
4楼-- · 2019-08-28 10:33

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;
查看更多
迷人小祖宗
5楼-- · 2019-08-28 10:44

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;
}
查看更多
登录 后发表回答