簡體   English   中英

PHP codeigniter獲取類別和子類別,其中子類別列表用逗號分隔

[英]PHP codeigniter to get categories and subcategories where subcategories list is seperated by comma

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

    //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
                        )

                )

        )
    )

請使用以下一項更新您的代碼

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

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

使用[]並檢查isset

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM