![](/img/trans.png)
[英]php foreach in foreach in foreach / for loop overwrite with last
[英]PHP Foreach in foreach loop
我有這么長的 foreach 代碼,我想用它來獲取文件夾和子文件夾 ID,以便能夠刪除它們。
// 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.', ';
}
}
}
}
}
這段代碼的問題在於,我必須為我想要進行的每次迭代編寫 foreach 語句。 我如何編寫一個簡單的循環或 function 來執行一次。 謝謝。
您可以將它放在一個方法中並使您的方法遞歸,因為可能存在動態嵌套調用,並且我們不確定要編寫多少 static foreachs。
片段:
<?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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.