[英]How to stop execution of PHP script when a certain condition is met in IF statement?
[英]How to stop a recursive loop when a certain condition is met in PHP
我有一個以下結構的數組,我想將元素從根級別獲取到第 3 級
Array
(
[0] => Array
(
[id] => 1
[parent_id] =>
[name] => try
[sub_categories] => Array
(
[0] => Array
(
[id] => 2
[parent_id] => 1
[name] => try1
[sub_categories] => Array
(
[0] => Array
(
[id] => 3
[parent_id] => 2
[name] => try2
[sub_categories] => Array
(
[0] => Array
(
[id] => 4
[parent_id] => 3
[name] => try3
[sub_categories] => Array
(
[0] => Array
(
[id] => 5
[parent_id] => 4
[name] => try4
)
)
)
)
)
)
)
)
(
[1] => Array
(
[id] => 6
[parent_id] => 1
[name] => try1
[sub_categories] => Array
(
[0] => Array
(
[id] => 7
[parent_id] => 6
[name] => try2
[sub_categories] => Array
(
[0] => Array
(
[id] => 8
[parent_id] => 7
[name] => try3
[sub_categories] => Array
(
[0] => Array
(
[id] => 9
[parent_id] => 8
[name] => try4
)
)
)
)
)
)
)
)
)
)
public function getElements( $parent_id = NULL, $level = 0 ) {
$data = models\Categories::find()->where( ['parent_id'=>$parent_id] )->all();
$arr = array();
foreach( $data as $data ) {
if( $level == 3 ) {
break;
}
//do something
$countChilds = models\Categories::find()->where( ['parent_id'=>$data->id] )->count();
if( $countChilds > 0 ){
$catData['sub_categories'] = $this->getElements( $parent_id = $data->id, $level++ );
}
$arr[] = $catData;
}
return $arr;
}
我嘗試添加一個計數器並在計數器達到 3 時跳出循環但它不起作用,所以我認為因為計數器只能在根類別旁邊的直接子類別上工作,因為我想go 在樹的第 3 層下,所以計數器不工作什么是實現這一目標的最佳方法我希望我的結果數組輸出一個 ID 為 1、2、3、4、6、7、8 的數組。 不應打印 ID 為 5,9 的元素,因為它們屬於級別 4
對此的任何幫助將不勝感激
這應該可以使用計數器來實現
$i = 0;
foreach($data as $item){
$i++;
if($i == 3) {
break;
}
}
或者一個for循環
for($i=0; $i<3; $i++){
}
<?php
public function getElements( $parent_id = NULL, $level = 0 ) {
if( $level == 3 ) return [];
$data = models\Categories::find()->where( ['parent_id'=>$parent_id] )->all();
$arr = array();
foreach( $data as $data ) {
//do something
$countChilds = models\Categories::find()->where( ['parent_id'=>$data->id] )->count();
if( $countChilds > 0 ){
$catData['sub_categories'] = $this->getElements( $parent_id = $data->id, $level + 1);
}
$arr[] = $catData;
}
return $arr;
}
在上面的代碼中,我做了 2 處更改。
$level == 3
,則立即返回。 無需將其放在 foreach 中。$catData['sub_categories'] = $this->getElements( $parent_id = $data->id, $level + 1);
而不是$level++
,因為子級將具有父級 + 1 並且后增量運算符不會這樣做。 此外,即使是++$level
(預增量操作)也不是一個好主意,因為即使對於 foreach 循環中的下一個即將到來的條目,您也在修改變量。 所以, $level + 1
是正確的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.