S
S
Sergey Bard2018-02-25 13:59:21
PHP
Sergey Bard, 2018-02-25 13:59:21

How to get all parent categories?

Hello everyone, the question is almost the same as here , but not quite, in general, the essence, I have a lot of nested subcategories. Also, products, a product can have only one category (in fact, there are not categories, but another entity, but for simplicity we will assume that this is a category), the product stores only one id of the category to which it is associated, how can I make it so that in product card, the name of the category to which the product and all parent categories are displayed?, the database itself looks something like this
id
parent_id
name
here is the same question as mine, but the answer does not fit, because I think what to do in the cycle request in bd with parent_id is not very clever, especially when the nesting is very large, I tried to do it like this

function getArrayParent($rows, $category_id) {
        foreach ($rows as $row) {
          if ($row['id'] == $category_id){
            if ($row['parent_id'] == 0){
              return $result[] = ['parent_id'=>0, 'name'=>$row['name']];
            } else {
              $result[] = ['parent_id'=>$row['parent_id'], 'name'=>$row['name']];
              getArrayParent($rows, $row['id']);					
            }
          }
        }
        return false;
      }
                       // $category_id - нужно найти всех родителей этой категории 
                       // $array- массив со всеми записями категорий
      $result = getArrayParent($array, $category_id);

those. I make a selection of all categories from the table, and then I sort through this array and try to find the parent categories, but this function causes me "Fatal error: Allowed memory size" (please tell me how else can I implement this?)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question