如何在php中从多维对象中访问值
以下是所讨论阵列的一部分:如何在php中从多维对象中访问值,php,simplexml,Php,Simplexml,以下是所讨论阵列的一部分: Array ( [Pricing] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [MType] => A
Array
(
[Pricing] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[MType] => A
[PType] => JBN
)
[PSNumber] => 19753
[CCode] => USD
[EDate] => 2008-12-19
[Price] => 218.23
)
现在我想访问'Ptype'和'Price'的值
“价格”很容易$a=(浮动)$Price\u a['Pricing'][0]>价格代码>
但我无法理解“Ptype”,我尝试了所有方法,最接近的是$price\u a['Pricing'][0]->{@attributes}
哪些产出:
SimpleXMLElement Object
(
)
我相信这有一个简单的解决方案,我错过了它,所以任何帮助都是感激的。谢谢大家! 不是吗:
$ptype = $price_a['Pricing'][0]->attributes()->Ptype;
$price_a['Pricing'][0]->attributes()->PType
razass,你必须改变你看待SimpleXML的方式。忘记对象和数组吧。不要使用var\u dump()
检查您的SimpleXMLElement
,否则您会感到困惑。您绝对不必将节点放在数组中来访问它们,这是没有意义的
在SimpleXML中,您可以使用->
(类似于对象的属性)访问节点,并像访问数组索引一样访问属性。比如说
$xml->node;
$xml['attribute'];
发布源XML,而不是发布var_dump()
的输出。例如,猜测一下实际的XML,代码如下
$Pricings = simplexml_load_string(
'<Pricings>
<Pricing MType="A" PType="JBN">
<PSNumber>19753</PSNumber>
<CCode>USD</CCode>
<EDate>2008-12-19</EDate>
<Price>218.23</Price>
</Pricing>
<Pricing MType="B" PType="XYZ">
<PSNumber>12345</PSNumber>
<CCode>USD</CCode>
<EDate>2008-12-19</EDate>
<Price>218.23</Price>
</Pricing>
</Pricings>'
);
// value of the first node's @PType
$Pricings->Pricing[0]['Ptype'];
// value of the first node's Price
$Pricings->Pricing[0]->Price;
// value of the second node's @PType
$Pricings->Pricing[1]['Ptype'];
$Pricings=simplexml\u load\u字符串(
'
19753
美元
2008-12-19
218.23
12345
美元
2008-12-19
218.23
'
);
//第一个节点的@PType的值
$Pricings->Pricing[0]['Ptype'];
//第一个节点的价格值
$Pricings->定价[0]->价格;
//第二个节点的@PType的值
$Pricings->Pricing[1]['Ptype'];
如果你的代码比这复杂,那你就是做错了,你只是在自找麻烦。请记住,它被称为SimpleXML。perfect,然后我只是在开头添加了(字符串)以获得值,而不是对象!“@”表示使用方法吗?ie)“attributes()”不,@attributes是SimpleXML内部使用的一个神奇属性。你绝对应该避免注意它。注意:SimpleXML使用了神奇的属性,var\u dump()
的输出可能会产生误导,通常应该避免。读我的答案。