2012-04-23 4 views
2

배열에 페이지 그룹을 정렬하고 부모 ID 번호에 따라 배치하려고합니다. 부모 ID가 0이면 내가 ...이 때문에 같은 배열로 배열에 배치하려는 배열 키가 다차원 배열에 존재합니다.

$get_pages = 'DATABASE QUERY' 
$sorted = array() 

foreach($get_pages as $k => $obj) { 
    if(!$obj->parent_id) { 
     $sorted[$obj->parent_id] = array(); 
    } 
} 

그러나 부모 ID가 설정되어있는 경우 나 관련 배열에 배치하고 싶습니다

, 다시 배열처럼 ...

$get_pages = 'DATABASE QUERY' 
$sorted = array() 

foreach($get_pages as $k => $obj) { 
    if(!$obj->parent_id) { 
     $sorted[$obj->id] = array(); 
    } else if($obj->parent_id) { 
     $sorted[$obj->parent_id][$obj->id] = array(); 
    } 
} 

여기가 내가 문제가되기 시작한 곳입니다. 배열의 2 차원에 삽입해야하는 세 번째 요소가 있거나 세 번째 차원에 삽입해야하는 네 번째 요소가있는 경우 해당 배열 키가 있는지를 확인할 방법이 없습니다. 그래서 내가 알아낼 수없는 것은 배열 키가 첫 번째 차원 뒤에 존재하는지 여부를 감지하는 방법과 어디에 있는지 확인하여 새로운 요소를 배치 할 수있는 방법입니다. 여기

여기에 내가 제안을 열려있어이 작업을 수행 할 수있는 더 좋은 방법이 있다면, 좀하고 싶습니다 출력의 예입니다 내 데이터베이스 테이블

id page_name parent_id 

1  Products    0 
2  Chairs    1 
3  Tables    1 
4  Green Chairs   2 
5  Large Green Chair 4 
6  About Us    0 

의 예입니다.

Array([1]=>Array([2] => Array([4] => Array([5] => Array())), [3] => Array()), 6 => Array()) 

고맙습니다.

답변

2

음, 기본적으로 당신이 나무를 구축하는 것은 그렇게 갈 수있는 방법 중 하나는 recursion 함께 :

// This function takes an array for a certain level and inserts all of the 
// child nodes into it (then going to build each child node as a parent for 
// its respective children): 

function addChildren(&$get_pages, &$parentArr, $parentId = 0) 
{ 
    foreach ($get_pages as $page) 
    { 
     // Is the current node a child of the parent we are currently populating? 

     if ($page->parent_id == $parentId) 
     { 
      // Is there an array for the current parent? 

      if (!isset($parentArr[ $page->id ])) 
      { 
       // Nop, create one so the current parent's children can 
       // be inserted into it. 

       $parentArr[ $page->id ] = array(); 
      } 

      // Call the function from within itself to populate the next level 
      // in the array: 

      addChildren($get_pages, $parentArr[ $page->id ], $page->id); 
     } 
    } 
} 


$result = array(); 
addChildren($get_pages, $result); 

print_r($result); 

이것은 당신이해야 & 계층을 이동하지만 페이지의 소수에 대한 가장 효율적인 방법이 아니다 좋아.

+0

고마워요! 나는 그것을 시도 할 것이다. 어떻게하면 더 효율적으로 만들 수 있을까요? – PapaSmurf

+0

매력처럼 일했습니다. 감사합니다! 그래도'! is_array'를'isset'으로 변경해야했습니다. – PapaSmurf

+0

그래, 그래 ...'isset'은 색인이 전혀 존재하지 않기 때문에 옳다. – Yaniro