2015-06-10 31 views
0

如何獲取的值Bar Foo如何獲取數組和物體的混合值

Array 
(
    [channel] => SimpleXMLElement Object 
     (
      [item] => Array 
       (
        [0] => SimpleXMLElement Object 
         (
          [title] => Bar Foo 
         ) 
       ) 
     ) 
) 
echo $sxml['channel']->item[$i]->title; 

它給結果,但注意:試圖如果你的對象的結構是這樣得到非對象

+5

「它給出結果,但通知」......什麼通知? – Khalid

+1

應該像'$ sxml [0] ['channel']一樣[ – cybersoft

+0

@Khalid注意:試圖獲取非對象的屬性 – saravanabawa

回答

0

的財產:(對象>陣列>對象>陣列),然後你打電話索引/鍵錯誤。注意下面的例子:

$x = new stdClass(); 
$x->channel = array(); 
$y = new stdClass(); 
$y->title = "Bar Foo"; 
$x->channel[0] = $y; 
//echo $x['channel']->item[$i]->title; 
//// Fatal error: Cannot use object of type stdClass as array 
echo $x->channel[0]->title; 
//// Success 

但是,如果它的結構你描述的方式,那麼你的回聲線給我正確的輸出(見下文),所以你可能會創建一個數組或對象的地方不能正確映射到您在上面的僞代碼中描述的內容。

$x = array(); 
$x['channel'] = new stdClass(); 
$x['channel']->item = array(); 
$x['channel']->item[0] = new stdClass(); 
$x['channel']->item[0]->title = "Bar Foo"; 
echo $x['channel']->item[0]->title; 

在一個側面說明,如果你發現你需要「美元符號」複雜的結構(如涉及數組索引動態變量名),你可以這樣做,使用括號是這樣的:

$x = 2; 
$y = array("x"=>$x); 
print $($y['x']);