N
N
nepster-web2013-12-28 22:35:34
PHP
nepster-web, 2013-12-28 22:35:34

Nested structure by lines, recursion

Tell me, please, how to solve the problem, recursion does not work:
There is a nesting tree:

- Овощи 
    - картошка
        - топинамбур 
    - капуста 
        - молодая 
        - старая 
    - буряк 
        - свежий 
 - Фрукты 
   - бананы 
   - яблоки 
   - груши 
- ягоды 
   - арбуз 
   - малина 
       - по дешевле 
       - по дороже

Nesting is represented by an array, all child elements of the element are in ['items'].
The task is this, you need to collect an array that will make this infinite nesting along the lines, that is:
[0] - 1 line
[0] Vegetables
[1] Fruits
[2] berries
[1] - 2 line
[0] - potatoes
[1] - cabbage
[2] - beetroot
[3] - bananas
[4] - apples
[5] - pears
[6] - watermelon
[7] - raspberries
[2] - 3 line
[0] Jerusalem artichoke
[1] young
[2] old
[3] fresh
[4] cheaper
[5] expensive
My experience:
function getStructToLine($getStruct, $tree = true)
    {
        $result = array();
        
        if($getStruct && is_array($getStruct))
        {
            foreach($getStruct as $line => $user)
            {
                
                if($tree)
                    $result[$line][] = $user['user_id'];
                else 
                    $result[$line] = $user['user_id'];
                
                
                if(isset($user['items']))
                {
                     $child = $this->getStructToLine($user['items'], false);
                     
                     $result[$line][] = $child;
                }
            }
        }
        
        return $result;
    }

It throws an error, although I don't understand why.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
veontomo, 2013-12-28
@veontomo

Three questions:
1. what is the exact structure of $getStruct?
2. With what parameters is getStructToLine() initially called?
3. what error is produced?
Probably typos:
1. 'user_id' key in $user['user_id']
2. $this->getStructToLine(...)

V
veontomo, 2013-12-29
@veontomo

If you haven't already, the advice is:
1. Your array of users is an object of class User with the properties
2. make the recursive function signature like this:
where Array is the storage that You need it as an answer and into which you need to gradually overtake the data from the first argument of the recursive function until it becomes "empty".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question