2013-03-26 103 views
0

我正在處理從XML文件轉換而來的多維PHP數組,並且努力從所有鍵名稱中獲取特定屬性(我不知道。所有鍵的名稱,但它們都具有相同的屬性)在PHP Foreach循環中獲取所有數組鍵的特定屬性

每個按鍵裏面的「$ player_stats」在數組中的結構是這樣的:

[RandomKeyName] => SimpleXMLElement Object 
    (
     [@attributes] => Array 
      (
       [assists] => 0.10 
       [rebounds] => 8 
       [operator] => > 
       [overall] => 1.45 
      ) 

    ) 

我想實現的東西像下面。使用$ key => $ value時,我無法從鍵獲取屬性?

foreach ($player_stats as $key => $value) { 

    $rebounds = $key->rebounds; 
    $assists = $key->assists; 

    echo "$key has $rebounds Rebounds and $assists Assists. <br>"; 
} 

$在這個例子中的關鍵工程,但屬性我試圖抓住沒有。任何提示或指針都可以在不知道鍵名的情況下獲取所有鍵的特定屬性,這很好,謝謝!

編輯:

的XML我想獲得的關鍵對象的一部分:

<Player_Stats> 
    <RandomKeyName1 assists="0.04" rebounds="9" operator="&gt;" overall="0.78" /> 
    <RandomKeyName2 assists="0.04" rebounds="4" operator="&gt;" overall="2.07" /> 
    <RandomKeyName3 assists="0.04" rebounds="1" operator="&gt;" overall="3.76" /> 
    <RandomKeyName4 assists="0.04" rebounds="10" operator="&gt;" overall="0.06" /> 
</Player_Stats> 
+0

$ value-> rebounds? – Patashu 2013-03-26 03:17:42

+0

這些鍵實際上並沒有在XML文件中的值,他們只是添加了屬性,這就是我所追求的。所以$值是空的。 foreach $ key => $ value只是我知道如何在不知道實際名稱的情況下訪問所有密鑰的唯一方式:/ – taylor 2013-03-26 03:21:52

+0

由於PHP數組深度不止一個級別,也許您的行爲不夠深入? – Patashu 2013-03-26 03:24:16

回答

0

如果我理解正確的話,$值是一個SimpleXMLElement對象。您可以使用SimpleXMLElement::attributes獲取屬性,您可以使用另一個foreach進行迭代。

這看起來像這樣(儘管我自己沒有測試過)。

foreach ($player_stats as $xmlKey => $xmlElement) { 

    foreach ($xmlElement->attributes() as $attrKey => $value) { 

     if ($attrKey === 'rebounds') 
      $rebounds = $value; 

     if ($attrKey === 'assists') 
      $assists = $value; 

    } 
    echo "$xmlKey has $rebounds Rebounds and $assists Assists. <br>"; 
} 
+0

這實際上工作沒有任何調整。完善!現在我對自己應該做的事情有了更好的理解。謝謝! – taylor 2013-03-26 03:49:07