Welcome Guest, Not a member yet? Register   Sign In
Little help with recursive function plz
#1

[eluser]Christophe28[/eluser]
Hi,

I'm trying to write a recursive function where the results ($item->id and $item->name) are returned in a multidimensional array:

This is how far I got in the category_model:

Code:
function get_childnodes($id) {
    
        // Create an array to store the childnodes
        $childnodes = array();
        
        // Select id, name and type of the deleted categories
        $q = "SELECT id, name, type FROM categories WHERE parent_id = ?";
        
        // Execute the query
        $sql = $this->db->query($q, array($id));
        
        // If there is a result ...
        if ( $sql->num_rows() > 0 ) {
        
            $results = $sql->result();
            
            foreach ( $results as $item ) {
                
                // If it is a category, search for more categories
                if ( $item->type == 0 ) {
                    
                    $this->category_model->get_childnodes($item->id);
                // echo $item->id . ' ';
                // echo $item->name . ' ';
                }
                
            }
        
        }
        
        // Return an array of ids
        return $childnodes;
        
    }
When you comment out the two echo statements, you get a nice line with the id's and names of all the childnodes (recursively, so also the children from the children, and so on ...)

The result I would be returned in the controller as follow:

Code:
$result_array = $this->category_model->get_childnodes($id);

print_r($result_array);

// RESULT
array(
    '0' => array(
            '0' => 'id_2',
            '1' => 'name'
            ),
    '1' => array(
            '0' => 'id_3',
            '1', 'other name'
            )
);

I hope somebody can help me out with this one!

Thanks in advance!

Christophe


Messages In This Thread
Little help with recursive function plz - by El Forum - 06-02-2011, 04:35 PM
Little help with recursive function plz - by El Forum - 06-02-2011, 07:35 PM
Little help with recursive function plz - by El Forum - 06-02-2011, 11:50 PM
Little help with recursive function plz - by El Forum - 06-03-2011, 12:44 AM
Little help with recursive function plz - by El Forum - 06-03-2011, 06:30 AM
Little help with recursive function plz - by El Forum - 06-10-2011, 03:40 AM
Little help with recursive function plz - by El Forum - 06-10-2011, 10:01 AM
Little help with recursive function plz - by El Forum - 06-11-2011, 01:53 AM
Little help with recursive function plz - by El Forum - 06-11-2011, 11:08 AM



Theme © iAndrew 2016 - Forum software by © MyBB