2009-05-08 5 views
4
I는 I 중첩 세트의 배열을 생성하기 위해이 함수를 발견이 spacetree 1) http://blog.thejit.org/wp-content/jit-1.0a/examples/spacetree.html

중첩 세트 PHP 배열 및 변환

위한 JSON로 내 중첩 세트 구조 (MySQL의) 변환해야

: 2) http://semlabs.co.uk/journal/converting-nested-set-model-data-in-to-multi-dimensional-arrays-in-php

또한 PHP 함수로 json_encode와 JSON에

내 문제를 PHP 배열로 변환 할 수 있습니다 : (두 번째 링크에서) 기능 nestify을 제공 나를 정확히 내가 필요. 다음과 같은 것이 필요합니다. http://pastebin.com/m68752352

올바른 배열을 제공하도록 "nestify"기능을 변경할 수 있습니까? 다음 코드는 트릭을 할해야

function nestify($arrs, $depth_key = 'depth') 
    { 
     $nested = array(); 
     $depths = array(); 

     foreach($arrs as $key => $arr) { 
      if($arr[$depth_key] == 0) { 
       $nested[$key] = $arr; 
       $depths[$arr[$depth_key] + 1] = $key; 
      } 
      else { 
       $parent =& $nested; 
       for($i = 1; $i <= ($arr[$depth_key]); $i++) { 
        $parent =& $parent[$depths[$i]]; 
       } 

       $parent[$key] = $arr; 
       $depths[$arr[$depth_key] + 1] = $key; 
      } 
     } 

     return $nested; 
    } 

답변

8

, 나는 웹에서 발견 된 일부 PHP 교리 코드에서 적응 : 여기

이 함수를 한 번 더입니다

function toHierarchy($collection) 
{ 
     // Trees mapped 
     $trees = array(); 
     $l = 0; 

     if (count($collection) > 0) { 
       // Node Stack. Used to help building the hierarchy 
       $stack = array(); 

       foreach ($collection as $node) { 
         $item = $node; 
         $item['children'] = array(); 

         // Number of stack items 
         $l = count($stack); 

         // Check if we're dealing with different levels 
         while($l > 0 && $stack[$l - 1]['depth'] >= $item['depth']) { 
           array_pop($stack); 
           $l--; 
         } 

         // Stack is empty (we are inspecting the root) 
         if ($l == 0) { 
           // Assigning the root node 
           $i = count($trees); 
           $trees[$i] = $item; 
           $stack[] = & $trees[$i]; 
         } else { 
           // Add node to parent 
           $i = count($stack[$l - 1]['children']); 
           $stack[$l - 1]['children'][$i] = $item; 
           $stack[] = & $stack[$l - 1]['children'][$i]; 
         } 
       } 
     } 

     return $trees; 
} 
+0

아무도 말해 줄 수 무엇 예를 들어,'$ stack [] = & $ trees [$ i];' –

+1

'은 스택에 트리 항목의 참조를 저장한다. 그것). 자세한 내용은 PHP 매뉴얼의 [References Explained] (http://php.net/manual/en/language.references.php) 장을 참조하십시오. – wimvds

+0

중요한 것. 이 함수를 사용하려면'left_id'에 의해'collection'의 주문 항목을 적용해야합니다 (중첩 된 세트 구조의 서비스 필드입니다). – userlond