简体   繁体   中英

PHP Change Array Order for Parent-Child Relation

Current Array Structure:

Array
(
    [0] => Array
        (

            [TASK_ID] => 2
            [PARENT_TASKID] => 0
            [TASK_LEVEL] => 0
        )

    [1] => Array
        (
            [TASK_ID] => 1
            [PARENT_TASKID] => 0
            [TASK_LEVEL] => 0
        )

    [2] => Array
        (
            [TASK_ID] => 4
            [PARENT_TASKID] => 1
            [TASK_LEVEL] => 1
        )

    [3] => Array
        (
            [TASK_ID] => 5
            [PARENT_TASKID] => 1
            [TASK_LEVEL] => 1
        )

    [4] => Array
        (
            [TASK_ID] => 6
            [PARENT_TASKID] => 5
            [TASK_LEVEL] => 2
        )

    [5] => Array
        (
            [TASK_ID] => 9
            [PARENT_TASKID] => 2
            [TASK_LEVEL] => 1
        )

    [6] => Array
        (
            [TASK_ID] => 10
            [PARENT_TASKID] => 2
            [TASK_LEVEL] => 1
        )
)

You can observe that PARENT_TASKID is TASK_ID for childs. For example:

Array
        (
            [TASK_ID] => 9
            [PARENT_TASKID] => 2
        )

Here TASK_ID = 9 is the child of TASK_ID = 2 . Note the PARENT_TASKID .

Array (
            [TASK_ID] => 2
            [PARENT_TASKID] => 0
            [TASK_LEVEL] => 0
        )

How can I change the above array format so the the child array comes under its parent and looks like below:

[0] => Array
    (

        [TASK_ID] => 2
        [PARENT_TASKID] => 0
        [TASK_LEVEL] => 0
    )

[1] => Array
    (
        [TASK_ID] => 9
        [PARENT_TASKID] => 2
        [TASK_LEVEL] => 1
    )

[2] => Array
    (
        [TASK_ID] => 10
        [PARENT_TASKID] => 2
        [TASK_LEVEL] => 1
    )

I do not what to place the children exactly beneath parents but change the array order accordingly.

What you want is called a topological sort. You can find some information on how to approach this here http://en.wikipedia.org/wiki/Topological_sorting

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM