简体   繁体   中英

How to prefix parent category to child category php

How to create a category prefixing its parent such as

category

category -> sub Category

category -> sub Category

category -> sub Category -> sub sub Category

category -> sub Category -> sub sub Category -> so on

here is Mysql table

|| id || name || parent_id || status || sort_order ||

any how tryied following to achive but i got only up to two levels ie category -> subcategory

here is my code

  $data['categories'] = array();
    foreach($categories as $category){
        
        if($category['parent_id'] != 0 && $category['parent_id'] != null){
           $name = $this->getparent($category['parent_id']) . '->' . $category['name'];
        } else {
            $name = $category['name'];
        }
        
        $data['categories'][] = array(
            'name' => $name,
            'id' => $category['id'],
            'sort_order' => $category['sort_order'],
            'status'    => $category['status'],
        );
    }

here is getParent() function

public function getparent($id){
        $model = new ModelCategory();
        $parent = $model->where('id', $id)->first();
        
        if($parent['parent_id'] != 0){
            
        }
        
        return $parent['name'];
        
    }

could anyone help me.. Thanks

you can call getparent() inside it

 public function getparent($id){
    $model = new ModelCategory();
    $parent = $model->where('id', $id)->first();
   
    if($parent['parent_id'] != 0){
           $name = $this->getparent($parent['parent_id']) . '->' . $parent['name'];
        } else {
            $name = $parent['name'];
        }
    
    
    return $name;

you already applied if() statement you were only few steps away to get desired.

Hope this answer might Help you

I think what you need is a recursive function. That's a function wich is calling itself based on a condition.

In your case, you don't know how many parents has you original category, so the condition is: "stop when there's no more parent id"

And the basic thing to do is: "append the parent category name to the current one"

Now in php it can be translated to:

public function getparent($id)
    {
        $model = new ModelCategory();
        $parent = $model->where('id', $id)->first();

        // your category HAS NO parent
        if (!$parent['parent_id']) {
            return ''; // no ancestor
        }

        $separator = '->';

        return $this->getparent($parent['parent_id']) . $separator . $parent['name'];
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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