0

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.

Community
  • 1
  • 1
Nepster
  • 144
  • 6
  • 2
    Could you provide the desired output for the example input you give? A bit larger input example would also be helpful. – trincot Feb 25 '16 at 09:47
  • The notion of *left* and *right* seems you expect a binary tree as input, but the input example has a root with three elements... that is not binary. – trincot Feb 25 '16 at 09:50
  • maybe interesting? [Zebra_Mptt, a PHP class providing an implementation of the modified preorder tree traversal algorithm](http://stefangabos.ro/php-libraries/zebra-mptt). Also, [How do you convert a parent-child (adjacency) table to a nested set using PHP and MySQL?](http://stackoverflow.com/questions/4664517/how-do-you-convert-a-parent-child-adjacency-table-to-a-nested-set-using-php-an?rq=1) – Ryan Vincent Feb 25 '16 at 10:15
  • You provided output, but it should be called a miracle if that output is derived from the input. The input has no mention of any of those *url, left* and *right* values you have there in the output. Where do they come from? – trincot Feb 25 '16 at 10:17
  • I use: https://github.com/creocoder/yii2-nested-sets – Nepster Feb 25 '16 at 10:18
  • 1
    That does not answer my question. – trincot Feb 25 '16 at 10:21
  • Sorry. URL is for convenience (this my correct example in db). We pay attention only to the ID. – Nepster Feb 25 '16 at 10:27

0 Answers0