phpzend-framework3laminas

PHP Foreach in foreach loop


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.


Solution

  • 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);
        }
    }