2016-08-04 161 views
0

我有兩個數據庫表類別和子類別。在類別表中,有一個字段子類別標識,其中存儲了用逗號分隔的子類別標識。我需要獲取類別和子類別。但我得到的子類別的只有最後一個值PHP codeigniter獲取類別和子類別的逗號分隔子類別列表

//Model 
public function getsubCategoriesbyId($subCategoriesId){ 
     $this->db->select('subCategoriesId, subCategoriesName'); 
     $condition = array('subCategoriesId'=>$subCategoriesId); 
     $this->db->where($condition); 
     $query = $this->db->get('subCategories'); 
     return $query->result(); 
    } 
public function getAllCategories(){ 
      $this->db->select('categoriesId, categoriesName, subCategoriesList'); 
      $query = $this->db->get('categories'); 
      $return = array(); 
      foreach($query->result() as $categoriesList){ 
       $return[$categoriesList->categoriesId]=$categoriesList; 
       $subCategoriesIdArray= explode(',', $categoriesList->subCategoriesList); 
       foreach($subCategoriesIdArray as $subCategoriesId){ 
          $return[$categoriesList->categoriesId]->subCategories = $this->getsubCategoriesbyId($subCategoriesId); 
       } 
      } 
      return $return; 
     } 
     //Controller 
public function mycontroller() 
{ 
     $data['categories_list']=$this->myModel->getAllCategories(); 
     echo "<pre>"; 
     print_r($data['categories_list']); 
     echo "</pre>"; 
     die(); 
} 
     //View 
Array 
    (
    [1] => stdClass Object 
     (
      [categoriesId] => 1 
      [categoriesName] => Nepal 
      [subCategoriesList] => 1, 2, 3, 4, 5, 6 
      [subCategories] => Array 
       (
        [0] => stdClass Object 
         (
          [categoriesId] => 6 
          [categoriesName] => Volunteer Tour 
         ) 

       ) 

     ) 
    ) 

回答

0

請與下面的一個

foreach($subCategoriesIdArray as $subCategoriesId){ 
    $return[$categoriesList->categoriesId]->subCategories = $this->getsubCategoriesbyId($subCategoriesId); 
} 

foreach($subCategoriesIdArray as $subCategoriesId){ 
    $return[$categoriesList->categoriesId]->subCategories[] = $this->getsubCategoriesbyId($subCategoriesId); 
} 

使用[]更新你的代碼,並檢查isset太

+0

你能幫我看看數組中的每個值? –

+0

首先告訴我問題解決了嗎?子類別 –

+0

thnx很多。它的工作正常 –