用于父子关系的PHP更改数组顺序

时间:2014-11-25 09:13:07

标签: php arrays

当前数组结构:

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
        )
)

您可以观察到PARENT_TASKIDTASK_ID为孩子。例如:

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

此处TASK_ID = 9TASK_ID = 2的孩子。请注意PARENT_TASKID

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

如何更改上面的数组格式,以便子数组位于其父元素下,如下所示:

[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
    )

我不知道将孩子放在父母的正下方,而是相应地更改数组顺序。

1 个答案:

答案 0 :(得分:0)

您想要的是拓扑排序。您可以在http://en.wikipedia.org/wiki/Topological_sorting

找到有关如何处理此问题的一些信息