【问题标题】:How to write category and subcategory with foreach?如何用foreach编写类别和子类别?
【发布时间】:2020-07-15 10:37:00
【问题描述】:

我有一个数据库类别表,有 3 个字段 id,name,cate 。我把它放入数组中

$select = $this->db->get_where('cate',array('cate >'=> 0))->result_array();

我想写一个foreach

if (cate == 1) : This is the main menu 
else if (cate == main menu id) : this is subcategory

这是我尝试过的

foreach ($select as $key => $value) {
    $id = $value['id']; 
    $name = $value['name'];
    $cate = $value['cate'];             
}

对不起我的英语不好

【问题讨论】:

    标签: php mysql arrays codeigniter


    【解决方案1】:

    这是我的解决方案:

    $categoriesHierchy = [];
    foreach ($categories as $mainCategory) {
        $childNode = [
            'id' => $mainCategory->getID(),
            'polishName' => $mainCategory->getPolishName(),
            'children' => findChildrenOfCategory($mainCategory)
        ];
        array_push($categoriesHierchy, $childNode);
    }
    
    public function findChildrenOfCategory($category)
    {
        $children = [];
        if (count($category->getChildren()) > 0) {
            foreach ($category->getChildren() as $child) {
                $childCategories = findChildrenOfCategory($child);
                $childNode = [
                    'id' => $child->getID(),
                    'polishName' => $child->getPolishName(),
                    'children' => $childCategories
                ];
                array_push($children, $childNode);
            }
        }
        return $children;
    }
    

    【讨论】:

      【解决方案2】:
      foreach ($select as $value) { //selecting each row/element
          $cate = $value['cate']; //grabbing column values
          $name = $value['name'];
          If($cate == 1){ //no need of cate == main cate id
             echo $name." is a main";
          }else{
             echo $name." is a sub";
          }             
      }
      

      【讨论】:

      • 口头解释通常很有帮助
      • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的答案以添加解释并说明适用的限制和假设。 From Review
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-05
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      相关资源
      最近更新 更多