가능한 중복 :
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
아래에서 다른 버전을 게시 할 예정입니다. –
Chris, 고맙습니다.하지만이 코드에서는 2보다 큰 차원을 가질 수 있습니다. 따라서 currentDepth = depth인지 확인하고 현재 요소에 대한 모든 경로를 인쇄하는 코드가 필요합니다. 따라서 배열에 5 차원 깊이가 있으면 $ url에 인쇄해야합니다. dimension1 = keydimension1 & dimension2 = keydimension2 & dimension3 = keydimension3 등 ... – Henrique