Fork me on GitHub

help with recursive function [resolved]  Bottom

  • theoretically this should work. dont know why it doesnt


    when i print out $cats right before i return it, the array prints out. BUT nothing returns to the main func from which it was called.

    background: i send a categoryID to the function, and it gets all the subcategories, and returns all the subCategoryIDs in an array.

    Code

    function pnListings_userapi_getCatList($args)
    {
        extract($args);

        if (!isset($cid)) {
            $cid = '';
        }
        $cats[] = array('cid' => $cid);
        $subcat = pnModAPIFunc('pnListings',
                             'user',
                             'getCatTree',
                              array('cid' => $cid));
    if(!$subcat) {
    print_r($cats);
    die;
        return $cats;

    }
        else
        {
          foreach ( $subcat as $subcatline){
                    pnModAPIFunc('pnListings',
                                         'user',
                                         'getCatList',
                                            array(
                                            'cid' => $subcatline[cid],
                                            'cats' => $cats));
            }
        }
    }
  • Code

    $cat = pnModAPIFunc('pnListings',
                             'user',
                             'getCatList',
                              array('cid' => $cid));
  • Code

    $cats[] = array('cid' => $cid);


    shoudl probably be imo :

    Code

    $cats = array('cid' => $cid);


    wink
  • Here's a recursive function that I wrote for my knowledge base:

    function steelkb_categories_build($catid='root', $categories_list = array()) {
    //recursive function to build a list of all categories

    pnModAPILoad('steelkb', 'user');
    $categories = pnModAPIFunc('steelkb', 'user', 'categories_get', array('parentid' => $catid));
    if($categories) {
    foreach($categories as $category) {
    $categories_list[] = $category['catid'];
    $categories_list = steelkb_categories_build($category['catid'], $categories_list);
    }
    }

    return $categories_list;
    }

    The API function gets sub categories for the given category.

    Hope that helps.
  • It looks like you don't actually return the value after the recursive call.
  • yes, jed, tht was the problem.

    i actually think i like chuck steel's solution, looks cleaner if someone else were to read the code.


    thanks for the help guys!

This list is based on users active over the last 60 minutes.