Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

246
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda