0

我需要编写一个递归函数来搜索一组父子链接头,然后获取每个头的嵌入键值的名称。前任。服装->男士->鞋子。现在,每个类别都有未知数量的附加值。我有一个函数可以成功地通过父母递归地回显所有这些值。但是当我尝试从函数中获取返回值时,它丢失了一些,我不明白为什么:/.

代码如下

public function getFamilies($cat){
            $objCurrentCategory = Category::Load($cat); // creates a QCodo object of the passed category ID.

        $str_Query = "SELECT DISTINCT p.family
                      FROM xlsws_product p, xlsws_product_category_assn pc
                      WHERE p.rowid=pc.product_id
                      AND pc.category_id=".$cat; // sql query to retrieve all Families relating to this category.

        $objFamilyDb = Family::GetDatabase(); // retrieves the QCodo database object for Family to execute queries against.
        $objFamilies = Family::InstantiateDbResult($objFamilyDb->Query($str_Query)); // executes the query and saves the result.

        foreach($objFamilies as $family){ // for each family returned, get the family name and add it to the array of names.
            if ($family->Family !== ""){
                $families [] = $family->Family;
            }
        }

        if ($objCurrentCategory->ChildCount > 0){ // if current category has children, create a list of all children rowids.
            $str_Query = "SELECT rowid FROM xlsws_category
                          WHERE parent=".$objCurrentCategory->Rowid; // query to get all children of the category.
            $objChildCategoriesDb = Category::GetDatabase(); // retrieves the QCodo database object for Category to execute queries against.
            $objChildCategories = Category::InstantiateDbResult($objChildCategoriesDb->Query($str_Query)); // executes the query and saves the result.

            foreach($objChildCategories as $child){ // passes through the children to get their families.
                //$families [] = KG::getFamilies($child->Rowid);
                $childFam = KG::getFamilies($child->Rowid);
            }
        }

        $compiled = KG::compileFamilies($childFam); // helper function, not important.


        foreach($compiled as $compile){
            $families[] = $compile;
        }

        foreach($families as $familyt){ // this echo statement correctly displays all names.
            //echo ":".$familyt."<br />";
        }

        return $families;
    }

因此,这会在函数运行期间通过回显到屏幕上显示所有名称,并且函数内的数组也可以回显到屏幕上。但是当我尝试在另一个页面中返回返回结果中的所有名称时,我错过了一堆名称。

编辑看起来 $families 变量并没有通过对 getFamilies 的每次递归调用持续存在,并且只在最后返回孩子,而不是孩子和他们所有的父母。

4

1 回答 1

0

固定的。问题是我试图在同一个递归语句中清理数组,并且由于返回了清理“帮助方法”而不是完整的关联数组,所以它把所有东西都扔掉了。叹息@我的健忘。

于 2012-07-13T14:52:23.207 回答