简体   繁体   English

如何遍历PHP中的stdObject元素数组?

[英]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: 这是我需要通过foreach循环访问的数据结构的print_r()版本:

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!! 但是我怎么把它放在foreach类型循环中呢!

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. 似乎该obj中有多个对象。您可能需要做更多的foreach循环。此代码应为您提供该obj中的第一个sessionId。

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

    }
}

run this code to see the obj in a clearer way: 运行以下代码以更清晰的方式查看obj:
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. 将“ $ detailedresponses”替换为正确的变量名称,然后将其重新发布回此处,这样会使内容更易于阅读。

EDIT 编辑
check out this URL, I put my test data in there: http://pastie.org/1130373 签出此URL,我将测试数据放在那里: 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 有一个很好的解决方案-有一个stdClass包含其他stdClases和数组

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. 您有一个所谓的php标准对象。 it's accessable like any other object in php by the $object->property syntax 它可以像$object->property语法一样访问php中的任何其他对象

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 . 因此,您可以通过以下方式对其进行迭代: foreach($object as $property)foreach($object as $prop_name => $prop_val) ,您可以在其中通过$object->$prop_name foreach($object as $prop_name => $prop_val)访问属性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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