M
M
mixejuxix2019-12-11 14:20:55
PHP
mixejuxix, 2019-12-11 14:20:55

How to convert a tree into multiple flat arrays?

Hello, there is a task to validate a tree using laravel, for this there are used rules, such as:

'questions.0.answers.0.questions.0.text' => 'required'
'questions.0.answers.0.questions.1.text' => 'required'
'questions.0.answers.1.questions.0.text' => 'required'

To generate such rules, I want to convert the tree into flat arrays, but I can't get to the algorithm :-(
For example, there is a tree:
Что будете есть?
        Торт
        Пирог
        Суп
            Какой?
                Борщ
                Солянка

You need to decompose it into arrays
['Что будете есть?']
['Что будете есть?', 'Торт']
['Что будете есть?', 'Пирог']
['Что будете есть?', 'Суп']
['Что будете есть?', 'Суп', 'Какой?']
['Что будете есть?', 'Суп', 'Какой?', 'Борщ']
['Что будете есть?', 'Суп', 'Какой?', 'Солянка']

In this case, the data is a little more complicated:
json

[
  {
    "text": true,
    "content": "Что будете есть?",
    "child": [
      {
        "text": true,
        "content": "Торт",
      },
      {
        "text": true,
        "content": "Пирог",
      },
      {
        "text": true,
        "content": "Суп",
        "child": [
          {
            "text": true,
            "content": "Какой?",
            "child": [
              {
                "text": true,
                "content": "Борщ",
              },
              {
                "text": true,
                "content": "Солянка",
              }
            ]
          }
        ]
      }
    ]
  }
]


And they need to be laid out accordingly in a two-dimensional array:
more or less like this

,




и так далее


Also, perhaps in laravel there are some more correct ways to validate a tree?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Khmelevsky, 2019-12-11
@socode

Greetings!
What you're after is most likely Laravel's own Helper Arr::dot .
I stuffed your json into dot and dumped it through dd(), got:
PS Accordingly, the algorithm for generating such a thing, you can look at the function in your IDE via Ctrl + LMB. (If you are using software from JetBrains)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question