Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
Remove elements from recursive array from bottom to top in PHP

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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!