Sane
Sane

Reputation: 31

Sort PHP array with children under parents

In this example I have an array of elements.

$array = ["Element A", "Element B", "Element C", "Element D", "Element E"]

After making a database call (I already figured this part out...), it is determined that "B" and "D" are children of element E. Additionally, "A" is a child of "C".

For demonstration purposes, parent($a) would return "c" while parent($e) would return NULL.

How can I reorder the array so that all children elements are directly below their parent elements?

The correct solution is something like these, where children are directly after parents:

["E", "B", "D", "C", "A"]
["E", "D", "B", "C", "A"]
["C", "A", "E", "B", "D"]
["C", "A", "E", "D", "B"]

Upvotes: 2

Views: 106

Answers (1)

VCNinc
VCNinc

Reputation: 757

The following general structure can outline how to order your issue.

if(CHILD) {
    if(PARENT EXISTS) {
        DELETE THIS ELEMENT
        INSERT AT LOCATION
    } else {
        DELETE THIS ELEMENT
        ADD PARENT
        RE-ADD THIS ELEMENT
    }
}

No specifics, just an outline...

Upvotes: 1

Related Questions