WebRTClerni
WebRTClerni

Reputation: 179

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 i.e 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

Upvotes: 1

Views: 865

Answers (2)

mbesson
mbesson

Reputation: 749

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'];
    }

Upvotes: 0

asimdev
asimdev

Reputation: 765

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

Upvotes: 1

Related Questions