2013-07-11 2 views
0
Array 
(
    [1] => Array 
     (
      [id] => 1 
      [parent_id] => 0 
      [name] => Men 
      [slug] => men 
      [status] => 1 
     ) 

    [2] => Array 
     (
      [id] => 2 
      [parent_id] => 1 
      [name] => Shoes 
      [slug] => shoes 
      [status] => 1 
     ) 


    [3] => Array 
     (
      [id] => 3 
      [parent_id] => 2 
      [name] => Sports 
      [slug] => sports 
      [status] => 1 
     )   
) 

여기 내 사이드 ​​바 메뉴 트리를 만드는 기능입니다.상위 슬러그를 가져 오는 계층 구조 트리

function ouTree($array, $currentParent, $currentLevel = 0, $previousLevel = -1) 
{ 
    foreach ($array as $categoryId => $category) 
    { 
     if ($currentParent == $category['parent_id']) 
     { 
      if ($currentLevel > $previousLevel) echo "<ul>"; 
      if ($currentLevel == $previousLevel) echo "</li>"; 
      echo "<li><a href='/category/{$category['slug']}' title='{$category['name']}'>{$category['name']}</a>"; 
      if ($currentLevel > $previousLevel) 
       $previousLevel = $currentLevel; 
      $currentLevel++; 
      ouTree ($array, $categoryId, $currentLevel, $previousLevel); 
      $currentLevel--; 
     } 
    } 
    if ($currentLevel == $previousLevel) echo "</li></ul>"; 
} 

ouTree($array, 0); 

현재 함수는 현재 슬러그 <a href="/category/men">Men</a> 만 호출합니다. 상위 슬러그를 현재 목록 순서로 검색하거나 반복하려면 어떻게합니까? 그래서이

<a href="/category/men">Men</a> 
<a href="/category/men/shoes">Shoes</a> 
<a href="/category/men/shoes/sports">Sports</a> 
+0

는'$ 동일 무엇 array'입니까? –

+0

@HalfCrazed 질문이 업데이트되었습니다. –

+1

개인적으로, 나는 그 배열을 전처리 할 것이므로 하위 카테고리는 부모 카테고리의 배열이므로 재귀 적으로 동일한 함수를 사용할 수 있습니다. – Lee

답변

2

OK처럼 될 것이다, 여기에 내가 몇 분 있었다뿐만이었다로 치아를 싱크하는 스크립트입니다. 의견을보세요! 그것은 스크립트의 모든 것을 설명합니다. 솔직히 말하면, 배열 구조를 복사 했으므로 곧바로 작동해야하지만 읽으면 이해할 수 있습니다. 맹목적으로 복사하여 붙여 넣기 만하면 안됩니다. 그런 식으로는 배우지 못할 것입니다 (정상적으로 작동하지 않을 것입니다. 코드,하지만 설명하기가 어렵습니다).

<?php 
/** 
* Heres your categories array structure, they can be in any order as we will sort them into an hierarchical structure in a moment 
*/ 
$categories = array(); 
$categories[] = array('id'=>5, 'parent_id' => 4, 'name' => 'Bedroom wear', 'slug' => 'bwear', 'status' => 1); 
$categories[] = array('id'=>6, 'parent_id' => 3, 'name' => 'Rolex', 'slug' => 'rolex', 'status' => 1); 
$categories[] = array('id'=>1, 'parent_id' => 0, 'name' => 'Men', 'slug' => 'men', 'status' => 1); 
$categories[] = array('id'=>2, 'parent_id' => 0, 'name' => 'Women', 'slug' => 'women', 'status' => 1); 
$categories[] = array('id'=>3, 'parent_id' => 1, 'name' => 'Watches', 'slug' => 'watches', 'status' => 1); 
$categories[] = array('id'=>4, 'parent_id' => 2, 'name' => 'Bras', 'slug' => 'bras', 'status' => 1); 
$categories[] = array('id'=>7, 'parent_id' => 2, 'name' => 'Jackets', 'slug' => 'jackets', 'status' => 1); 


/** 
* This function takes the categories and processes them into a nice tree like array 
*/ 
function preprocess_categories($categories) { 

    // First of all we sort the categories array by parent id! 
    // We need the parent to be created before teh children after all? 
    $parent_ids = array(); 
    foreach($categories as $k => $cat) { 
     $parent_ids[$k] = $cat['parent_id']; 
    } 
    array_multisort($parent_ids, SORT_ASC, $categories); 

    /* note: at this point, the categories are now sorted by the parent_id key */ 

    // $new contains the new categories array which you will pass into the tree function below (nothign fancy here) 
    $new = array(); 

    // $refs contain references (aka points) to places in the $new array, this is where the magic happens! 
    // without references, it would be difficult to have a completely random mess of categories and process them cleanly 
    // but WITH references, we get simple access to children of children of chilren at any point of the loop 
    // each key in this array is teh category id, and the value is the "children" array of that category 
    // we set up a default reference for top level categories (parent id = 0) 
    $refs = array(0=>&$new); 

    // Loop teh categories (easy peasy) 
    foreach($categories as $c) { 

     // We need the children array so we can make a pointer too it, should any children categories popup 
     $c['children'] = array(); 

     // Create the new entry in the $new array, using the pointer from $ref (remember, it may be 10 levels down, not a top level category) hence we need to use the reference/pointer 
     $refs[$c['parent_id']][$c['id']] = $c; 

     // Create a new reference record for this category id 
     $refs[$c['id']] = &$refs[$c['parent_id']][$c['id']]['children']; 

    } 

    return $new; 

} 

/** 
* This function generates our HTML from the categories array we have pre-processed 
*/ 
function tree($categories, $baseurl = '/category/') { 

    $tree = "<ul>"; 

    foreach($categories as $category) { 

     $tree .= "<li>"; 

     $tree .= "<a href='".$baseurl.$category['slug']."'>".$category['name']."</a>"; 

     // This is the magci bit, if there are children categories, the function loops back on itself 
     // and processes the children as if they were top level categories 
     // we append the children to the main tree string rather tha echoing for this reason 
     // we also pass the base url PLUS our category slug as the "new base url" so it can build the URL correctly 
     if(!empty($category['children'])) { 

      $tree .= tree($category['children'], $baseurl.$category['slug'].'/'); 

     } 

     $tree .= "</li>"; 


    } 

    $tree .= "</ul>"; 

    return $tree; 

} 

///echo "<pre>"; print_r(preprocess_categories($categories)); die(); 
echo tree(preprocess_categories($categories)); 
?> 

을 heres 페이스트 빈 링크는 꽤 색깔을 좋아하는 경우 코드 : http://pastebin.com/KVhCuvs3

+0

좋은 캐치 & 잘 설명했습니다. (y) –

+0

첫 번째 ul에만 ID 또는 클래스를 제공하려면 어떻게해야합니까? –

+1

트리 함수 내부에 체크를하고 첫 번째 UL 인 경우 클래스/ID를 추가하십시오. 당신은'$ baseurl'이 기본값 인지를 검사 할 수 있습니다. 또는 함수 매개 변수에 $ level이라는 다른 매개 변수를 추가 할 수 있습니다.이 매개 변수는'0'에서 시작하여'tree()'가 내부에서 호출되면 증가합니다. 그런 다음 레벨 0에만 클래스를 추가 할 수 있습니다. – Lee