2013-09-27 35 views
0

我是PHP中這個關聯數組概念的新手。現在我有一個數組命名爲$sample如下:如何從PHP中的關聯數組中訪問特定的鍵?

Array 
(
    [name] => definitions 
    [text] => 
    [attributes] => Array 
    (
    [name] => Mediation_Soap_Server_Reporting 
    [targetnamespace] => https://mediation.moceanmobile.net/soap/reporting 
) 
    [children] => Array 
    (
    [types] => Array 
    (
     [0] => Array 
     (
     [name] => types 
     [text] => 
     [attributes] => Array 
     (
     ) 
     [children] => Array 
     (
      [xsd:schema] => Array 
      (
      [0] => Array 
      (
       [name] => schema 
       [text] => 
       [attributes] => Array 
       (
       [targetnamespace] => https://mediation.moceanmobile.net/soap/reporting 
      ) 
       [children] => Array 
       (
       [xsd:complextype] => Array 
       (
        [0] => Array 
        (
        [name] => complextype 
        [text] => 
        [attributes] => Array 
        (
         [name] => Mediation_Soap_FaultMessage 
        ) 
        [children] => Array 
        (
         [xsd:sequence] => Array 
         (
         [0] => Array 
         (
          [name] => sequence 
          [text] => 
          [attributes] => Array 
          (
         ) 
         ) 
        ) 
        ) 
       ) 
       ) 
      ) 
      ) 
     ) 
     ) 
    ) 
    ) 
) 
) 

從上面的陣列我想引用(或訪問)鍵XSD:模式。但我無法做到。您能否告訴我應該如何從聯想陣列名稱$sample訪問或引用此密鑰?提前致謝。

+0

我想你想要:'$ sample ['children'] ['types'] [0] ['children'] ['xsd:schema']'? – Christoph

回答

1

要訪問此值,你可以使用: -

$sample['children']['types'][0]['children']['xsd:schema']; 

如果你在你的types陣列這些元素的多,你會通過他們需要循環: -

foreach($sample['children']['types'] as $type) { 
    if(isset($type['children']) && isset($type['children']['xsd:schema'])) { 

     // Perform action on element 
     $type['children']['xsd:schema']; 

    } 
} 

如果你這樣做不知道你的結構(因爲xsd:schema可能發生在types之外),那麼你將需要編寫一個遞歸函數或循環來找到它。

+0

其實我已經放了一小部分數組。該數組比我上面粘貼的代碼大得多。如果我想訪問關鍵字爲xsd:schema的所有數組元素,我應該怎麼做?我應該使用foreach還是wht?你能指導我嗎?謝謝你的回答。 – PHPLover

+0

是的,爲了訪問所有名爲xsd:schema的元素,您必須遍歷數組。我會更新我的答案以反映這一點。 –

0

我想你的目標是尋找密鑰/值對的關鍵是「xsd」?

如果是這樣,在PHP中,你可以通過使用follwing邏輯這樣做:

while (list($key, $value) = each($arr)) { 
    echo "Key: $key; Value: $value<br />\n"; 
} 
// OR 
foreach ($arr as $key => $value) { 
    echo "Key: $key; Value: $value<br />\n"; 
} 

只需添加一組遞歸或嵌套的循環遍歷這個結構,直到找到正確的密鑰。

+0

另外,當首先創建數組時,請確保使用「somekey」而不僅僅是某個鍵作爲鍵。它必須是一個字符串。如果你忘記了它,它仍然看起來像在工作,但它可能不會運行在我上面建議的代碼中。 – Tuthmosis

相關問題