Codeigniter: retrieve values from the out-of-loop array

Asked

Viewed 1,195 times

1

I’m having 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 $cat_id variable correctly stores the values of my query, when I echo in:

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

But if 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 only the last stored id.

I need to store all the 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 that?

Grateful.

1 answer

2


What happens is that every time he loops the last value will always be stored, so doing this every time the loop runs will override the previous value. To create an array you must do 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 in:

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

The echo is inside the foreach and will be called every time there is an execution on foreach.

In this section of your code, if I’m not mistaken the correct 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;
  • Thank you Diego.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.