Search code examples
phpcodeigniter

codeigniter misbehave: function in main controller works as expected but in helper return empty array


I have following function which retrieve parent category from table then save it to an array until no one found. this function works just fine when it be called in main controller directly from url browser, but when it be called from codeigniter helper and feeds to count() function return empty array with no element in it.

// in codeigniter helper:
function get_category_ancestors($catId)
{
    $ci =& get_instance();
    static $categoryAncestors = array();
    $category = $ci->a_model->get_cat_parent($catId);
    if($category->num_rows() > 0)
    {
        $categoryParent = $category->row_array();
        $categoryAncestors[][$categoryParent["id"]] = $categoryParent["categoryName"];
        get_category_ancestors($categoryParent["id"]);
    }
    else
    {
        $inOrder = array_reverse($categoryAncestors);
        return $inOrder;
    }
}
// model: (for clear demonstration)
// two table: category and category_relation
public function get_cat_parent($categoryId)
{
    $this->db->select('category.*' );
    $this->db->from('category_relation');
    $this->db->where('category_relation.subCategoryId', $categoryId);
    $this->db->join('category', 'category.id=category_relation.categoryId');
    $query = $this->db->get();
    return $query;
}
// some other helper:(get_category_ancestors() caller)
$categoriesInOrder = get_category_ancestors($categoryId);   
$totallAncestors = count($categoriesInOrder); // =>error: Parameter must be an array or an object that implements Countable

Solution

  • have to return get_category_ancestors to works. return get_category_ancestors($categoryParent["id"]); not just get_category_ancestors($categoryParent["id"]);.