2017-06-21 18 views
0

我在php和codeigniter ramework環境中創建類別樹結構時遇到問題。php codeigniter中樹數據的算法

所以現在我想要的數據結構。

數據舉例:

{ 
    "category": [ 
     { 
      "id"  : "1", 
      "text" : "test1" 
      "children": false, 
     }, { 
      "id"  : "2", 
      "text" : "test2", 
      "children": [ 
       { 
        "children": false, 
        "id"  : "3", 
        "text" : "test3" 
       }, { 
        "children": false, 
        "id"  : "4", 
        "text" : "test4" 
       }, { 
        "children": false, 
        "id"  : "5", 
        "text" : "test5" 
       }, { 
        "children": false, 
        "id"  : "6", 
        "text" : "test7" 
       } 
      ] 
     } 
    ] 
} 

我無法創建每個JSON對象的兒童

查詢我想一個數組:

public function setCategoryTree($categoryUp = null) 
    { 
    $param = array(); 

    $query = ' SELECT id, name, categoryUp 
       FROM categoryTable 
        WHERE categoryUp = ? '; 


    return $this->commerce_db->query($query)->result(); 
    } 

控制器我想到:

public function getCategoryTree(){ 
    $this->load->model('category_m'); 
    $result = $this->category_m->setCategoryTree(); 
    $resultData = array(); 

    foreach($result as $value) { 
     $treeTmpData = array(); 
     $treeTmpData['id'] = $value->id; 
     $treeTmpData['text'] = $value->text; 
     $treeTmpData['children'] = ????  
     $resultData[] = $treeTmpData; 
    } 

    echo json_encode($resultData, JSON_UNESCAPED_UNICODE); 

    } 

祝我好運

+0

請提供categoryTable的結構。 –

回答

0

您可以使用此代碼爲您的目的。我使用遞歸獲取childern。

表結構爲:

CREATE TABLE `categorytable` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `name` varchar(50) DEFAULT NULL, 
    `parent_id` int(11) DEFAULT NULL, 
    PRIMARY KEY (`id`) 
); 

型號的方法有:

public function setCategoryTree() { 
     $categories = array(); 
     $query = $this->db->query('SELECT id, name as text, parent_id as children FROM categoryTable WHERE parent_id IS NULL'); 
     foreach ($query->result() as $row) { 
      $child = $this->getChilderen($row->id); 
      if (count($child) > 0) { 
       $row->children = $child; 
      } else { 
       $row->children = false; 
      } 
      $categories[] = $row; 
     } 
     return $categories; 
    } 

    private function getChilderen($parentId) { 
     $child = array(); 
     $query = $this->db->query('SELECT id, name as text, parent_id as children FROM categoryTable WHERE parent_id = ' . $parentId); 
     if (count($query->result()) > 0) { 
      foreach ($query->result() as $i => $row) { 
       if ($row->children > 0) { 
        $row->children = $this->getChilderen($row->id); 
       } 
       $child[$i] = $row; 
      } 
      return $child; 
     } else { 
      return false; 
     } 
    } 

控制器代碼:

public function getCategoryTree(){ 
    $this->load->model('category_m'); 
    $resultData = $this->category_m->setCategoryTree(); 
    echo json_encode($resultData, JSON_UNESCAPED_UNICODE); 
} 

希望,這將幫助你。讓我知道你是否卡在某個地方。