2011-09-28 6 views
2

가능한 중복 :
Walk array recursively and print the path of the walkPHP 다차원 배열 재귀 문제

사람이 날이 코드를 도울 수 있는가?

<?php 
function buildMenuWalk(&$array, &$depth, $currentDepth = 1) 
    { 
     # start new level html 
     $html = ''; 

     # walk till the depth defined on the config 
     if($currentDepth > $depth) 
     { 
      return null; 
     } 

     # loop through all items in this level 
     foreach($array as $key => &$value) 
     {  
      # if not in area map continue 
      if(!is_numeric($key)) 
      { 
       continue; 
      } 

      # if no <li> has been created yet, open the <ul> 
      $html .= empty($html) ? '<ul class="dropdown">' : ''; 

      #extract the label from this level's array, designated by $labelKey 
      $label = isset($value['areaname']) ? $value['areaname'] : ''; 

      # open an <li> 
      $html .= '<li>'; 

      # generate url 
      $url = ''; 
      if($currentDepth == $depth) 
      { 
       $url = ' href="'. 

       $url .= '"'; 
      } 

      # construct content inside the <li> 
      $html .= '<a' . $url .'>' . $label . '</a>'; 


      # run the function again to grab children levels 
      if(is_array($value)) 
      { 
       $html .= buildMenuWalk($value, $depth, $currentDepth + 1); 
      } 

      # close <li> 
      $html .= '</li>'; 
     } 

     # close <ul> if was generated content on this level 
     $html .= !empty($html) ? '</ul>' : ''; 

     return $html; 
    } 
$depth = 2; 

$config['content']['map'][1]['areaname'] = 'area_1'; 
$config['content']['map'][1][1]['areaname'] = 'block_1'; 
$config['content']['map'][2]['areaname'] = 'area_2'; 
$config['content']['map'][2][1]['areaname'] = 'block_1'; 
$config['content']['map'][2][2]['areaname'] = 'bloack_2'; 

echo buildMenuWalk($config['content']['map'], $depth); 
?> 

위의 코드를 확인하면

, 스크립트 태그 안에 = ""href가 표시됩니다, 메뉴가 깊이에 도달 식별 경우

... 재귀 메뉴를 표시하기 위해 사용 임. 이 href 안에 재귀에 모든 부모 영역을 추가하고 싶습니다. 예를 들어

: 스크립트 bloack_2 이르면

, I는 표시해야

$config['content']['map'][2]['areaname'] = 'area_2'; 
$config['content']['map'][2][1]['areaname'] = 'block_1'; 
$config['content']['map'][2][2]['areaname'] = 'bloack_2'; 
:

<a href="area_2=2&block_2=2"> 
의 다차원 배열 이후

성장할 수 4-5 사이즈처럼 출력 HREF 수행해야 이 모든 수준을 세십시오. 예를 들어 area_2 = 1 & block_10 = 5 & sub_area_1 = 5 & section_7 = 8 ...

아마 재귀 동안 모든 HREF 경로를 저장하는 일부 배열이 필요하지만, 내가 그것을 어떻게 질수 그림.

감사합니다,

PS : 스크립트는 드롭 다운 메뉴를 구축하는 데 사용됩니다. 부모 레벨은 연결될 필요가 없으므로 태그를 인쇄하면 하위 메뉴가 표시됩니다. 마지막 자식은 연결되지만 결과를 필터링 할 수 있도록 모든 부모 매개 변수를 포함해야합니다. 코드 실행 및 반환 값

링크 : http://codepad.org/iyrcdfQP

답변

0

이 기능은 자신을 재귀 적으로 호출되기 때문에, 당신은 이전 트리를 추적하기 위해 글로벌 변수를 참조해야합니다. 그래서 여기에 내가하고 싶은대로 할 코드가 있습니다. 모두 변경해야하는 부분은 #generate url 섹션입니다.

# generate url 
$url = ''; 
if($currentDepth == $depth) { 
    $url = " href=area=" . $GLOBALS['area'] . "&block=$key"; 
} else { 
    $GLOBALS['area'] = $key; 
} 
+0

아래에서 다른 버전을 게시 할 예정입니다. –

+0

Chris, 고맙습니다.하지만이 코드에서는 2보다 큰 차원을 가질 수 있습니다. 따라서 currentDepth = depth인지 확인하고 현재 요소에 대한 모든 경로를 인쇄하는 코드가 필요합니다. 따라서 배열에 5 차원 깊이가 있으면 $ url에 인쇄해야합니다. dimension1 = keydimension1 & dimension2 = keydimension2 & dimension3 = keydimension3 등 ... – Henrique

0

다음은 href =를 설명하는 것과 조금 더 비슷하게 만드는 동일한 코드 조각을 수정 한 것입니다. 실제로는 나에게 의미가 없지만 말입니다.

# generate url 
    $url = ''; 
    if($currentDepth == $depth) { 
     $url = " href=".$GLOBALS['area_name']."=".$GLOBALS['area']."&$label=$key"; 
    } 
    else { 
     $GLOBALS['area'] = $key; 
     $GLOBALS['area_name'] = $label; 
    } 
+0

Henrique,이 코드가 문제를 해결합니까? –

0

하나의 웹 페이지가있는 메뉴와 2 차원의 세계에 recursoin과 여러 차원으로 귀찮게 왜 나는 볼 수 없습니다!

나는 2 차원 갈 것입니다 만, 첫 번째 차원은 요소에 대한 정보를 정기적으로 유지하기 위해 (어떤 기준없이) 모든 요소와 두 번째 유지하는 것입니다 :

enter image description here

자신을 위해 예를 확인을, 함수를 가져올 요소를 설정하여 이전 레벨의 모든 상위 요소 및 루트 요소와 함께 표시합니다 (캘리포니아처럼).

<?php 
function buildMenuWalk($element,$menuElements) 
{ 
    for($i=0;$i<=$element;$i++) 
    { 
     //for a new level go to the next line 
     if(!isset($menuElements[$i]['ancestors'])) 
     { 
      echo '<br>______________________________________</br>'; 
      echo '<strong>',$menuElements[$i]['label'],'</strong> | '; 
     } 
     //if the element is reached display it along with ancestors 
     if($i==$element) 
     { 
      //echo all the ancestores 
      foreach($menuElements[$element]['ancestors'] as $value) 
      { 
       echo $menuElements[$value]['label'],' | '; 
      } 
      //display the element itself 
       echo '<font color=red>',$menuElements[$element]['label'],' | </font>';   
     } 
    } 
} 

//California 
$menuElements[0]=Array('url'=>'http://www.California.com','label'=>'California'); 
$menuElements[1]=Array('url'=>'http://www.San Diego.com','label'=>'San Diego','ancestors'=>Array(0)); 
$menuElements[2]=Array('url'=>'http://www.San Jose.com','label'=>'San Jose','ancestors'=>Array(0,1)); 
$menuElements[3]=Array('url'=>'http://www.San Francisco.com','label'=>'San Francisco','ancestors'=>Array(0,1,2)); 
$menuElements[4]=Array('url'=>'http://www.Fresno.com','label'=>'San Francisco','ancestors'=>Array(0,1,2,3)); 
$menuElements[5]=Array('url'=>'http://www.Sacramento.com','label'=>'Sacramento','ancestors'=>Array(0,1,2,3,4)); 

//Wyoming 
$menuElements[6]=Array('url'=>'http://www.Wyoming.com','label'=>'Wyoming'); 
$menuElements[7]=Array('url'=>'http://www.Cheyenne.com','label'=>'Cheyenne','ancestors'=>Array(6)); 
$menuElements[8]=Array('url'=>'http://www.Casper.com','label'=>'Casper','ancestors'=>Array(6,7)); 
$menuElements[9]=Array('url'=>'http://www.Laramie.com','label'=>'Laramie','ancestors'=>Array(6,7,8)); 
$menuElements[10]=Array('url'=>'http://www.Gillette.com','label'=>'Gillette','ancestors'=>Array(6,7,8,9)); 
$menuElements[11]=Array('url'=>'http://www.Rock Springs.com','label'=>'Rock Springs','ancestors'=>Array(6,7,8,9,10)); 

echo '<pre>'; 
buildMenuWalk(9,$menuElements); 

?> 
+0

정말 질문이 아닙니다. 단일 메뉴를 반환하는 함수를 만들었고 여러 차원이있는 메뉴의 드롭 다운 메뉴가 필요했습니다. – Henrique