繁体   English   中英

如何用foreach编写类别和子类别?

[英]How to write category and subcategory with foreach?

我有一个数据库类别表,有 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'];             
}

我为我糟糕的英语感到抱歉

这是我的解决方案:

$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;
}
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";
    }             
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM