从PHP中的另一个函数调用递归函数

问题描述:

I have created a recursive function which returns the array value. So I am calling that function from another function. but it doesn't return any values. The function is given below,

public function sitemapAction() {
    $sites = self::getNavigation();
    foreach(self::recursiveSitemap($sites) as $url) {
    ...
    ...
    }
}

public function recursiveSitemap($sites)
{
    $result = array();
    foreach ($sites as $site) {
        $result[]= array($site['DFA']);
        if (is_array($site['items'])) {
            return recursiveSitemap($site['items']);
        }
    }
}

Please help me on this.

我创建了一个返回数组值的递归函数。 所以我从另一个函数调用该函数。 但它不会返回任何值。 该函数如下, p>

  public function sitemapAction(){
 $ sites = self :: getNavigation(); 
 foreach(self :: recursiveSitemap($ sites)  as $ url){
 ... 
 ... 
} 
} 
 
公共函数recursiveSitemap($ sites)
 {
 $ result = array(); 
 foreach($ sites as  $ site){
 $ result [] = array($ site ['DFA']); 
 if(is_array($ site ['items'])){
 return recursiveSitemap($ site ['items']  ); 
} 
} 
} 
  code>  pre> 
 
 

请帮助我。 p> div>

If you look carefully at your recursive method, you will see that it actually does not return anything at all:

public function recursiveSitemap($sites)
{
    $result = array();
    foreach ($sites as $site) {
        $result[]= array($site['DFA']);
        if (is_array($site['items'])) {
            return recursiveSitemap($site['items']);
        }
    }
}

If your variable $site['items'] is an array you call your method again, going deeper, without doing anything with the returned value.

And if not?

It would seem you would need to add the result you get back from your recursive function call to your $result array and return that, but I don't know exactly what output you expect.

Apart from that you have a small typo, you need self::recursiveSitemap($site['items']) if you want to call the same method recursively.

A simple example:

public function recursiveSitemap($sites)
{
    $result = array();
    foreach ($sites as $site) {
        if (is_array($site['items'])) {
            // do something with the result you get back
            $result[] = self::recursiveSitemap($site['items']);
        } else {
            // not an array, this is the result you need?
            $result[]= array($site['DFA']);
        }
    }
    // return your result
    return $result;
}

Assuming that $result is the thing you want to get back...