V
V
Vladimir Ivakhnenko2014-11-12 20:50:36
PHP
Vladimir Ivakhnenko, 2014-11-12 20:50:36

How to parse formatted text into a tree in PHP?

There is some text like this:

Категория1
[tab]Подкатегория1
[tab]Подкатегория2
[tab][tab]ПодПодкатегория1
[tab][tab]ПодПодкатегория2
[tab][tab][tab]ПодПодПодкатегория1
[tab]Подкатегория3
Категория2
[tab]Подкатегория4

[tab] - tab character.
Please tell me the algorithm how to turn this into PHP in PHP
[
  [
    'name' => 'Категория1',
    'children' => [
      [
        'name' => 'Подкатегория1',
        'children' => []
      ],
      [
        'name' => 'Подкатегория2',
        'children' => [
          [
            'name' => 'ПодПодкатегория1',
            'children' => []
          ],
          [
            'name' => 'ПодПодкатегория2',
            'children' => [
              [
                'name' => 'ПодПодПодкатегория1',
                'children' => []
              ]
            ]
          ]
        ]
      ]
    ]
  ],
  [
    'name' => 'Категория2',
    'children' => [
      [
        'name' => 'Подкатегория4',
        'children' => []
      ]
    ]
  ]
]

For some reason, the code formatting is not saved.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2014-11-12
@c_basso

Head-on solution - we calculate the level by the number of indents and recursively bypass the list. Something like this:
ideone.com/u7xAv9

A
Anton Shamanov, 2014-11-12
@SilenceOfWinter

Similar case How to build an xml tree from a path?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question