简体   繁体   中英

Recursive function not working as expected php

I have ebay categories that have parent_id s. The top level category doesn't have a parent_id . I am trying to write a recursive function that will return me an array from lowest category to highest eg:

array
    0 => string '27"' 
    1 => string 'Monitors' 
    2 => string 'TV, Monitors and Display' 

So far, however, it's causing an infinite loop. I think it's because the parent_id isn't being passed when the function is called again, it's using the $ebay_store_category_id from what was passed the first time the function was called rather than parent_id .

public static function get_ebay_cats($ebay_store_category) {
    $cat_array = array();
    $ebay_store_category_id = $ebay_store_category->category_id;
    $array = self::get_cat_array($ebay_store_category_id, $cat_array);
}

private function get_cat_array($ebay_store_category_id, &$cat_array, ) {
    $ebay_cat_model = new Ebay_store_category_model($ebay_store_category_id);
    $ebay_cat_model->get();
    $cat_array[$ebay_cat_model->category_id] = $ebay_cat_model->name;
    $parent_id = $ebay_cat_model->parent_id;
    echo 'parent id :'.$parent_id.' | current category id: '.$ebay_cat_model->category_id.'<br/>';

    if(!empty($parent_id)) {
        return self::get_cat_array($parent_id, $cat_array);
    }

    return $cat_array;
}

The results of the echo

How I know its infinite and the parent id is not being passed when the function references itself:

parent id :6692320015 | current category id: 6697237015 parent id :6692320015 | current category id: 6697237015 parent id :6692320015 | current category id: 6697237015 parent id :6692320015 | current category id: 6697237015 parent id :6692320015 | current category id: 6697237015

My table structure:

+------------+------------+-------------------------------+-------+-------------+
| id         | parent_id  | name                          | order | category_id |
+------------+------------+-------------------------------+-------+-------------+
| 7          | NULL       | TV, Monitors and Displays     |     0 | 7           |
| 6701115015 | 7          | Monitors                      |     4 | 6701115015  |
| 5661200015 | 6701115015 | 27"                           |     3 | 6701114015  |

It's a CI thing. I used $ebay_cat_model->get_where(array('id'=>$ebay_store_category_id)); instead of $ebay_cat_model = new Ebay_store_category_model($ebay_store_category_id); and it works now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM