2013-09-27 4 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

당신이 사용하는 것이이 값에 액세스하려면 : - 당신은 당신의 types 배열이 요소의 복수가있는 경우

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

당신이 그들을 통해 루프 필요를 -

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가 아닌 somekey를 키로 사용해야합니다. 문자열이어야합니다. 그 사실을 잊어 버리면 작동하는 것처럼 보이지만 위의 코드에서 실행되지 않을 수 있습니다. – Tuthmosis

관련 문제