CodeIgniter Forums

Full Version: Database Query not displaying expected output.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]JasonS[/eluser]
I have a category structure which looks like this.

Bike
- New
Cars

Bike is the parent of New.

I am trying to create a query which will generate an array to display the above output.

What I have currently outputs

Bike
- New

But Cars gets lost. Could someone have a peek and tell me where I am going wrong.

Cheers.
Code:
$this->db->where('parent', '0');
        $query = $this->db->get('categories');
        
        $count = 0;
        
        foreach($query->result() as $row)
        {
            $array[$count]['id'] = $row->id;
            $array[$count]['name'] = $row->name;
            
            $this->db->where('parent', $row->id);
            $newquery = $this->db->get('categories');
            if ($newquery->num_rows() > 0)
            {
                foreach($newquery->result() as $newrow)
                {
                    $array[$count]['id'] = $newrow->id;
                    $array[$count]['name'] = '  - ' . $newrow->name;
                }
            }
            
            $count++;
        }

El Forum

[eluser]Sumon[/eluser]
You miss increment the counter $count for inner for loop.

Try to use this one
Code:
foreach($query->result() as $row)
        {
            $array[$count]['id'] = $row->id;
            $array[$count]['name'] = $row->name;
            
            $this->db->where('parent', $row->id);
            $newquery = $this->db->get('categories');
            if ($newquery->num_rows() > 0)
            {
                foreach($newquery->result() as $newrow)
                {
                    $count++;
                    $array[$count]['id'] = $newrow->id;
                    $array[$count]['name'] = '  - ' . $newrow->name;
                }
            }
            
            $count++;
        }