2009-05-11 4 views
2

이것이 명확하지 않은 경우 나에게 곰이 있습니다. 이 문제를 해결하기 위해 머리를 감싸는 데 어려움을 겪고 있습니다.재귀의 추적 깊이

Array 
(
[DimA1] => Array 
    (
     [DimB1] => Array 
      (
       [DimC1] => Array 
        (
         [value1] => 13708 
         [value2] => 4.5 
        ) 

       [DimC2] => Array 
        (
         [value1] => 1846 
         [value2] => 15.8 
        ) 

      ) 

     [DimB2] => Array 
      (
       [DimC1] => Array 
        (
         [value1] => 18166 
         [value2] => 6.4 
        ) 
      ) 
[DimA2] => Array 
    (
     ....... etc 

나는이 배열을 통해 단계를 필요로하고 내가 값 1과 값 2에 도착하면, 나는 일부 데이터베이스 삽입을 수행해야합니다

나는 다음과 같습니다 배열을 가지고있다. 지금이 시점에서, 나는 현재 어떤 배열을 사용 중인지 알고 있어야하며, 데이터베이스 삽입의 일부로 키 이름을 사용해야합니다.

내 현재 솔루션은 다음과 같습니다

public function recurseCounts($array,$dims = array()) { 
    foreach ($array as $key => $value) { 
     $dims[] = $key; 
     if (isset($value['value1']) || isset($value['value2'])) { 
      print_r($value); // For debugging... 
      print_r($dims); // For debugging... 
          // DB Logic to insert dimensions in to DB here 
          // DB Logic to insert values in to DB here 
      array_pop($dims); 
     } else { 
      $this->recurseCounts($value,$dims); 
     } 
    } 
} 

이 루프가 DimB2 안타 지점까지 작동 상황이 괴팍스러운 받기 시작 곳이 있습니다.

해결 방법에 대한 아이디어가 있으십니까?

답변

2

.

은 $ 어두워 이제 갈 것입니다 :

DimA1 
DimA1, DimB1 
DimA1, DimB1, DimC1 
DimA1, DimB1, DimC2 
DimA1, DimB1, DimB2 
DimA1, DimB1, DimB2, DimC1 
DimA1, DimB1, DimB2, DimC2 

당신이 확인을해야하는 경우가 외부로 array_pop를 이동합니다.

public function recurseCounts($array,$dims = array()) { 
    foreach ($array as $key => $value) { 
      $dims[] = $key; 
      if (isset($value['value1']) || isset($value['value2'])) { 
        print_r($value); // For debugging... 
        print_r($dims); // For debugging... 
         // DB Logic to insert dimensions in to DB here 
         // DB Logic to insert values in to DB here 
      } else { 
        $this->recurseCounts($value,$dims); 
      } 
      array_pop($dims); 
    } 

}

1

당신은 동일 깊이 "C"에서 키 이후 요소에 대한 전체 경로를 추적해야합니다 당신은 항상 $에 희미을 추가

public function recurseCounts($array,$dims = array(),$path = '') { 
     foreach ($array as $key => $value) { 
       $dims[] = ($path ? $Path.'_' : '').$key; // Add the full path (separated by '_') 
       if (isset($value['value1']) || isset($value['value2'])) { 
         print_r($value); // For debugging... 
         print_r($dims); // For debugging... 
          // DB Logic to insert dimensions in to DB here 
          // DB Logic to insert values in to DB here 
         array_pop($dims); 
       } else { 
         $this->recurseCounts($value,$dims,end($depth)); // pass it on 
       } 
     } 
}