2016-06-16 3 views
1

데이터베이스에 테이블이 있고이 테이블에 i, name, parent_id.please라는 3 개의 열이 추가되었습니다.PHP를 사용하여 테이블에서 계층 구조 만들기

ID | name | parent_id 

    1 name1 0 
    2 name2 1 
    3 name3 1 

이제 데이터베이스에서이 ID를 가져 오려고합니다. 나는 PHP에서 메소드를 만들고 데이터베이스에서 하나씩 데이터를 가져온다. 내가 그

Array(
    [0]=>name1 
) 

처럼 돌아갑니다

$this->getData(3); // has a parent 

같은 ID 3이 메소드를 호출하면 이제

function getData($id) 
{ 
      $array = array(); 
      $db = JFactory::getDBO(); 
      $sql = "SELECT * from table_name when id = ".$id; 
      $db>setQuery($sql); 
      $fetchAllDatas = $db->getObjectList(); 

      foreach ($fetchAllDatas as $fetchAllData) 
      { 
       if($fetchAllData->parent_id > 0) 
       { 
        $array[$fetchAllData->parent_id] = $fetchAllData->name; 
        $this->getData($fetchAllData->parent_id); 
       } 
       else 
       { 
        $array[$fetchAllData->parent_id] = $fetchAllData->name; 
       } 
      } 
      return $array; 
} 

아래를 참조하지만 난 싶지하십시오 같은

Array(
    [1]=>name3, 
    [0]=>name1 
) 
아래

나는 배열을 재정의했다는 것을 안다 if 우리에게는 부모가 있지만 어떻게 관리 할 수 ​​있습니까? array_push PHP 함수를 사용했지만 내 조건에서 작동하지 않습니다.

+0

'SELECT * from table_name id = some_id'는이 쿼리가 작동합니까 ??? –

답변

-1

테이블에 고유 한 ID가 있으므로 쿼리를 호출하면 항상 하나의 결과 만 반환됩니다. 어쩌면 당신은 이런 식으로 쿼리를 쓰고 싶다 : 당신이 주어진 ID와 그의 부모와 함께 결과를 얻으려면

$sql = "SELECT * from table_name when parent_id = ".$id; 

, 당신은 $ this-> fetchSharedFolder (...) 호출 한 후이를 추가해야을; 당신이 경우와 다른 사람의에서 $array[$fetchAllData->parent_id] = $fetchAllData->name;을하기 때문에

$array = array_merge($array, $this->getData($fetchAllData->parent_id)); 
+0

fetchSharedFolder를 getData로 변경할 때 작동합니까? array_merge로 감싸는 것을 잊지 마라. getData는 다른 배열을 현재 $ array로 반환하고있다. –

1
  foreach ($fetchAllDatas as $fetchAllData) 
      { 
      $array[$fetchAllData->parent_id] = $fetchAllData->name; 
      if($fetchAllData->parent_id > 0) 
        array_push($array,$this->getData($fetchAllData->parent_id));     
      } 
      return $array; 

1), 당신은 너무 if..else에서 넣어 두 경우 모두에서이 작업을 수행. 2) 두 번째 호출 결과를 원본 배열로 밀어 넣어 원하는 결과를 얻으십시오.

+0

나는 그것을 테스트했고 그것은 나를 위해 일했다. – CiroRa