J
J
jekahm2014-09-01 21:01:07
PHP
jekahm, 2014-09-01 21:01:07

How does the category tree generation function work?

Good day!
On the Internet, I found a function for implementing a category tree. But when it was parsed, I did not finally understand how exactly it works.
The implementation of the function itself is here .
I'm interested in exactly how in this piece of code

foreach ($categories as &$category) {
        $map[$category['parent']]['subcategories'][] = &$category;
    }

nested arrays (of different levels of nesting) are formed? I understand that this happens when passing by reference. But how do they appear?
Thanks in advance for your reply!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Sokharev, 2014-09-02
@greabock

in the code from the link you provided, the most subtle point is:
is actually the same (short syntax) as

array_push(
    $map[$category['parent']]['subcategories'],
    &$category
);

$category['parent'] is the id of the category. Let's say it's 0 .
That is,a reference to $categories[0 ] will be added to the $map[0]['subcategories'][0] array . If there is another category with the same [parent] , then the link to it will be written in $map[0]['subcategories'][1] . Well, as in the line, it says that the category in the map ( $map ), refers to the category in the list ( $categories ). Then they are set by reference recursively. the interpreter looks in the subcategory - there are links, it looks in the subcategory of links - there are links again, and so on, until the nesting reaches the end.

J
jekahm, 2014-09-02
@jekahm

TO greabock :
It's not entirely clear how this recursion is called.
Here I have made the output of the $map array on each iteration of the loop. Could you explain to me how a nested array arises, for example, in the so-called. section with code name Parent => 2--------------------Category => 6 (line 787 ):

[0] => Array
            (
               [id] => 6
               [parent] => 2
               [name] => Subcategory F
               [subcategories] => Array
               (
               )

            )

Maybe then based on this I can understand the basic principle

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question