我有一个对象,其中包含我想要遍历的对象数组。对象的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等等。
任何人都可以解释为什么我没有得到预期的钥匙?我需要做些什么来获得钥匙?
答案 0 :(得分:0)
这是因为simpleXML结构不是普通数组,而是没有数组索引的迭代器。
手动维护自己索引的解决方案。