How to convert php hierarchical array in nested sets?

878

I have a hierarchical array.

Array
(
    [0] => Array
        (
            [id] => 28
        )

    [1] => Array
        (
            [id] => 29
        )

    [2] => Array
        (
            [id] => 30
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 31
                        )

                )

        )

)

I need to get keys «left», «right» and «depth» for nested sets.

I found a similar question here: php convert array into a hierarchical nested set for database.

But answer from this branch doesn’t work correctly.

It doesn’t have key «depth» and calculation of keys «left» and «right» is not correct.

Expected Result:

Array
(
    [0] => Array
        (
            [id] => 27
            [lft] => 1
            [rgt] => 10
            [depth] => 0
        )

    [1] => Array
        (
            [id] => 28
            [lft] => 2
            [rgt] => 3
            [depth] => 1
        )

    [2] => Array
        (
            [id] => 29
            [lft] => 4
            [rgt] => 5
            [depth] => 1
        )

    [3] => Array
        (
            [id] => 30
            [lft] => 6
            [rgt] => 9
            [depth] => 1
        )

    [4] => Array
        (
            [id] => 31
            [lft] => 7
            [rgt] => 8
            [depth] => 2
        )
)

[id] => 27 - : this is a root node, but I do not show it to users.

Please help me to solve this problem.

People are also looking for solutions to the problem: php - How to get all the sum of individual id?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.