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.
My Answer:
>getIdsToDelete($folders);
foreach ($idsToDelete as $id) {
// second foreach code
$subfolders = $this->getSubfolders($id);
foreach ($subfolders as $subfolder) {
// delete subfolder
$this->deleteSubfolder($subfolder);
}
// delete folder
$this->deleteFolder($id);
}
In this code snippet, the first foreach loop is used to get the ids of folders that need to be deleted. Then, for each folder id, a second foreach loop is used to get the subfolders of that folder and delete them. Finally, the folder itself is deleted.
Rate this post
3 of 5 based on 5848 votesComments