我正在编写一个对类别进行排序的模块,并向我返回最低的子类别。
private function getChild($array){
foreach($array as $item){
if(is_array($item)){
$this->getChild($item);
} else {
array_push($this->catsToReturn, $item);
}
}
}
所以我的实际问题是,为什么我不能在其他外壳中返回值?我想返回$ item并将该值推入数组,这将使我具有更好的代码可读性,因为现在我有了
$this->getChild($this->postCategories);
随机挂在我的代码中。
对我来说,奇怪的是,我可以回显该值,但我无法返回它,我知道这是范围问题,但是找不到有关如何解决它的任何信息。
只是想知道如何改进它。
欢呼声
您可以通过在数组中添加$item
并执行array_merge
以获取后续调用的结果来更改代码。
array_merge
无论您在课堂上叫什么地方,都可以做
<?php
private function getChild($array){
$result = [];
foreach($array as $item){
if(is_array($item)){
$result = array_merge($result,$this->getChild($item));
} else {
$result[] = $item;
}
}
return $result;
}