O
O
Oleg2018-03-01 20:17:31
PHP
Oleg, 2018-03-01 20:17:31

How to build a category tree based on products?

I need to build a category tree based on the products in a table.
There is a table with products added by the user (wishlist_products) (wishlist_id, product_id)
There is a table with categories, where each category has a parent (parent_id). The main category (to which all the others are linked) has id = 0
The category output format looks like this:

Array
(
    [category_id] => 3
    [parent_id] => 2
    [name] => Фэтбайки
)

I have an array with all the product ids added by the user - $product_ids
I can get the product categories (Not the main category, but the child category the product is currently linked to) :
//например в таблице есть только один продукт, у которого категория Фэтбайки(id = 3)
$categories = $this->category->getCategoriesByProducts($product_ids);
В результате: 
[0] => 3 // категория Фэтбайки

Also, I can get a list of categories that go above (parent_id) Fatbikes:
Using the function:
$this->category->getParentsCategories(3) // получаем категорию 3 и ее родителей в виде:
[0] => 1 // Спорт
[1] => 2 //Велосипеды
[2] => 3 //Фэтбайки

I need to build the correct array of the form:
Array
(
  [0] => Array ( // Главная категория дочерней категории.
                    [cat_id] => 1
                    [text] => Спорт 
                    [nodes] => Array ( //Тут Второй уровень категории
                               [0] => Array (
                                                  [cat_id] => 2
                                                  [text] => Велосипеды
                                                  [nodes] => Array (   //Тут Третий уровень категории
                                                            [0] => Array (
                                                                               [cat_id] => 3
                                                                               [text] => Фэтбайки
                                                                               [nodes] => 
                                                              )
                                                   )
                                 )
                       )
        )
)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Lykasov, 2018-03-02
@lykasov-aleksandr

adjacency list to help you:
https://habrahabr.ru/post/46659/xandeadx.ru/blog/php/199
https
://www.codesd.com/item/recursive-php-function...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question