CodeIgniter Forums
Get array without tree`s structure after recursion - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Get array without tree`s structure after recursion (/showthread.php?tid=53577)



Get array without tree`s structure after recursion - El Forum - 07-30-2012

[eluser]Unknown[/eluser]
Hello, everybody!

Help me please.
Depending on category, I need to output all the products from the subs and from the current category.

More detail:
My table of catalog [catalog_id,title,parent_id] and products[id, catalog_id].
Graphic scheme of my cat-data:

1(0)-2(1)-3(2)
-4(2)
4(0)-5(4)
6(0)

When user open for example catalog_id=1 must be output all products from 1,2,3,4 categories or when catalog_id = 2 only 2, 3 and 4 cats.

For this reason I used recursive function:

Code:
public function get_ids($cid)
{
    
    $qry = $this->db->select('catalog_id')
                    ->from('catalog')
                    ->where('parent_id',$cid)
                    ->get();

    $arrResult = array();

    if($qry->num_rows > 0) {
        
        $t = $qry->result_array();
        
        foreach($t as $row){
            $arrResult[$row['catalog_id']] = $this->get_ids($row['catalog_id']);
        }

    }

    return $arrResult;
}
So I got next array (when catalog_id = 1):
Array ( [2] => Array ([3] => Array() [4] => Array() )

Than I need use recursion again to get all the products. And it`s too difficult and too much weight.

How can I simplify this task?
Maybe there is possibility to get array without tree`s structure:
Array ( [2] => array(catalog_id =>2) [3] => array(catalog_id =>3) [4] => array(catalog_id =>4) ) ?