繁体   English   中英

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

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

这是我需要通过foreach循环访问的数据结构的print_r()版本:

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

            [1] => stdClass Object
                ( 
...

现在,如何遍历这些对象?

我可以感觉到我应该做这样的事情:

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

但是我怎么把它放在foreach类型循环中呢!

似乎该obj中有多个对象。您可能需要做更多的foreach循环。此代码应为您提供该obj中的第一个sessionId。

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

    }
}

运行以下代码以更清晰的方式查看obj:
echo '<pre>'; print_r($detailsresponses); exit;

将“ $ detailedresponses”替换为正确的变量名称,然后将其重新发布回此处,这样会使内容更易于阅读。

编辑
签出此URL,我将测试数据放在那里: http : //pastie.org/1130373

我重新创建了您要获取的对象,并在其中添加了注释,以便您了解发生了什么:)

并且,您可以获得以下属性:

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

有一个很好的解决方案-有一个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;
}

很简单。 您有一个所谓的php标准对象。 它可以像$object->property语法一样访问php中的任何其他对象

因此,您可以通过以下方式对其进行迭代: 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