2009-11-27 66 views
2

这里访问值是有问题的数组的一个切片:如何从多维对象中的PHP

Array 
(
    [Pricing] => Array 
     (
      [0] => SimpleXMLElement Object 
       (
        [@attributes] => Array 
         (
          [MType] => A 
          [PType] => JBN 
         ) 

        [PSNumber] => 19753 
       [CCode] => USD 
       [EDate] => 2008-12-19 
       [Price] => 218.23 
      ) 

现在我要访问“P型”和“价格”的值。

“价格”是很容易$a = (float) $price_a['Pricing'][0]->Price;

但我无法弄清楚“P型”我已经尝试了一切,我得到的最接近是$price_a['Pricing'][0]->{@attributes}

,输出:

SimpleXMLElement Object 
(
) 

我相信这有一个简单的解决方案,我错过了,所以任何帮助表示赞赏。谢谢!

回答

2
$ptype = $price_a['Pricing'][0]->attributes()->Ptype; 
+0

完美,然后我刚刚添加(字符串)到开始只得到的价值,而不是对象!现在'@'是否表示使用方法?即)'attributes()' – user103219 2009-11-27 21:43:24

+0

不,@attributes是SimpleXML内部使用的魔术属性。你一定要避免关注它。 **注意:** SimpleXML使用魔术属性,'var_dump()'的输出可能非常具有误导性,通常应避免。阅读我的答案。 – 2009-11-28 00:41:19

2

是不是:

$price_a['Pricing'][0]->attributes()->PType 
2

razass,你绝对要改变你的SimpleXML的方式。忘记对象和数组。做不是var_dump()检查你的SimpleXMLElement或者你会一直困惑。你一定要而不是必须把节点放入数组来访问它们,这是没有意义的。

SimpleXML中,你使用->(如一个对象的属性)和属性,如果他们数组索引访问节点。例如

$xml->node; 
$xml['attribute']; 

而不是发布的var_dump()输出,发表您的XML源。例如,采取猜测您的实际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']; 

如果你的代码是任何复杂多了,你这样做是错误的,你只是在自找麻烦。请记住,它叫做简单的 XML。