循环遍历包含对象数组的对象


Loop through an object containing an array of objects

我有一个对象,它包含一个要循环通过的对象数组。对象的print_r如下所示:

SimpleXMLElement Object
(
    [NewDataSet] => SimpleXMLElement Object
        (
            [Table1] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [DiamondID] => 44696069
                            [ShapeTitle] => Pear
                            [Weight] => 0.300
                            [ColorTitle] => G
                        )
                    [1] => SimpleXMLElement Object
                        (
                            [DiamondID] => 44775332
                            [ShapeTitle] => Pear
                            [Weight] => 0.300
                            [ColorTitle] => G
                        )
                    [2] => SimpleXMLElement Object
                        (
                            [DiamondID] => 46959935
                            [ShapeTitle] => Pear
                            [Weight] => 0.340
                            [ColorTitle] => D
                        )
                )
        )
)

该对象来自我正在通过SOAP调用检索的一些XML。

我想循环遍历"Table1"数组,访问每个对象。我通过:

foreach($rapnetresult->NewDataSet->Table1 as $itemno=>$diamond) {
  echo "<p>Item #$itemno<br>";
  echo "DiamondID: " . $diamond->DiamondID . "<br>";
  echo "ShapeTitle: " . $diamond->ShapeTitle. "<br>";
  echo "Weight: " . $diamond->Weight"</p>";
}

这会产生以下输出:

Item #Table1
DiamondID: 44696069
ShapeTitle: Pear
Weight: 0.300
Item #Table1
DiamondID: 44775332
ShapeTitle: Pear
Weight: 0.300
Item #Table1
DiamondID: 46959935
ShapeTitle: Pear
Weight: 0.340

这就是我想要的,在那里我可以访问每个对象。然而,我对$itemno变量为什么总是具有值"Table1"感到困惑。我本以为它是Table1数组键,即:0、1、2等。

有人能解释一下为什么我没有得到预期的钥匙吗?我该怎么办才能拿到钥匙?

之所以会发生这种情况,是因为simpleXML结构不是普通的数组,而是没有数组索引的迭代器。

解决方案是手动维护自己的索引。