Codeigniter: retrieve array values out of loop

1

I have a problem storing the array values in the code below:

public function get_submenu() {
    $query = $this->db->get_where('categories', array('category_id_parent' => 0));

    foreach ($query->result() as $row):
        $cat_id = $row->category_id;
    endforeach;

    if ($cat_id != FALSE):
        $this->db->from('categories');
        $this->db->where('category_id_parent', $cat_id);
        $query = $this->db->get();
        return $query;
    else:
        return FALSE;
    endif;
}

Inside the loop, the variable $ cat_id correctly stores the values of my query, when I echo:

foreach ($query->result() as $row):
    $cat_id = $row->category_id;
    echo $cat_id;
endforeach;

But if the echo is out of the loop, like this:

foreach ($query->result() as $row):
    $cat_id = $row->category_id;
endforeach;

echo $cat_id;

What returns is just the last id stored.

I need to store all values of the $ cat_id array to retrieve in the subsequent if block:

if ($cat_id != FALSE):
        $this->db->from('categories');
        $this->db->where('category_id_parent', $cat_id);
        $query = $this->db->get();
        return $query;
    else:
        return FALSE;
    endif;

How do I do this?

Thank you.

    
asked by anonymous 03.07.2014 / 10:50

1 answer

2

What happens is that every time the loop is executed the last value will always be stored, so doing this every time the loop rotates will overwrite the previous value. To create an array you should do it as follows.

$cat_id = array();
foreach ($query->result() as $row):
        $cat_id[] = $row->category_id;
    endforeach;

Further explaining your code:

Inside the loop, the $ cat_id variable correctly stores the values of my query, when I echo:

foreach ($query->result() as $row):
    $cat_id = $row->category_id;
    echo $cat_id;
endforeach;

The echo is within foreach and will be called every time there is an execution in foreach .

In this section of your code, if I'm not mistaken, the correct one would be to use $this->db->where_in() , because it is a array .

if ($cat_id != FALSE):
        $this->db->from('categories');
        $this->db->where_in('category_id_parent', $cat_id);
        $this->db->where('category_id  !=', 0);
        $query = $this->db->get();
        return $query;
    else:
        return FALSE;
    endif;
    
03.07.2014 / 14:04