1

I have this long foreach code I want to use to get folders and subfolders ids in order to be able to delete them.

// first foreach code       
$idsToDelete = $this->entityManager->getRepository(Folders::class)
            ->findBy(['parentId'=>$postId]);
foreach ($idsToDelete as $d){
    $postId = $d->getId(); echo $postId.', ';
    
    //second foreach code in first foreach
    $idsToDelete = $this->entityManager->getRepository(Folders::class)
                    ->findBy(['parentId'=>$postId]);
    foreach ($idsToDelete as $d){
        $postId = $d->getId(); echo $postId.', ';
        
        //third foreach code in second foreach
        $idsToDelete = $this->entityManager->getRepository(Folders::class)
                    ->findBy(['parentId'=>$postId]);
        foreach ($idsToDelete as $d){
            $postId = $d->getId(); 
            echo $postId.', ';
            
            //forth foreach code in third foreach
            $idsToDelete = $this->entityManager->getRepository(Folders::class)
                    ->findBy(['parentId'=>$postId]);
            foreach ($idsToDelete as $d){
                $postId = $d->getId(); echo $postId.', ';
            
                //fith foreach code in forth foreach
                $idsToDelete = $this->entityManager->getRepository(Folders::class)
                        ->findBy(['parentId'=>$postId]);
                foreach ($idsToDelete as $d){
                    $postId = $d->getId(); echo $postId.', ';
                }
            }
        }
    }
}

the problem with this code is that, I will have to write foreach statement for each iteration I want to make. How do I write a simple loop or function to do this once. Thanks.

1 Answer 1

0

You can put this inside a method and make your method recursive since there could be dynamic nested calls and we wouldn't be sure how many static foreachs to write.

Snippet:

<?php

public function deleteIDs($postId){
    $idsToDelete = $this->entityManager->getRepository(Folders::class)
            ->findBy(['parentId' => $postId]);
    foreach ($idsToDelete as $d){
       $currPostId = $d->getId(); echo $currPostId.', ';
       $this->deleteIDs($currPostId);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.