1

Given the following array:

array(
    0 => array(
        0 => 56,
        1 => array(
            0 => 57,
            1 => 58,
            2 => 59,
        ),
        2 => 60
    ),
    1 => array(
        0 => 61,
        1 => array(
            0 => 62,
            1 => array(
                0 => 63,
                1 => 64
            )
        )
    )
)

How could I proceed to remove elements from that array starting from deepest elements? My elements are ID in a database and key constraints make me unable to delete parents if they have children...

I looked for something using RecursiveIterator but no solution so far...


EDIT

Actually, no need to get a specific algo, a standard recursion will do the job

4
  • You need to traverse the array from the deepest element to the parent element to delete the records from Database. right? Commented Apr 28, 2017 at 12:04
  • Yes, but I can achieve this from parents to children: if my parent has children, go through the children and delete. Then recheck if it still has children. If no, delete it and go on Commented Apr 28, 2017 at 12:06
  • Can you explain little bit more. you need the Ids in the form of 56, 57, 58 ...? Commented Apr 28, 2017 at 12:20
  • I need to remove first 57, 58, 59, then, 56, then 60, then 63, 64, then 62, then 61 Commented Apr 28, 2017 at 12:22

1 Answer 1

2

You can visit leaves only with RecursiveIteratorIterator and RecursiveIteratorIterator::LEAVES_ONLY mode and then reverse the resulting array:

$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($ids),
    RecursiveIteratorIterator::LEAVES_ONLY
);

$ids = [];

foreach ($iterator as $id) {
    // You can put elements directly in the beggining of an array
    // or reverse array later.
    // array_unshift($ids, $id);
    $ids[] = $id;
}

$ids = array_reverse($ids);

Here is working demo.

Sign up to request clarification or add additional context in comments.

1 Comment

That's it! Great! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.