Search code examples
phparrayscodeigniterpopulate

Get values from database on the basis of values in array


I need to populate a dropdown list on the basis of the values in an array. This is my code.

Suppose a user has ids 1,2,3. Then the table_group corresponding to these ids must be selected and displayed in a dropdown. Also there should not be any repeating values like in this case in id 2 and 3 value 23 repeats, in this case only one value will be taken. Here $table_id is fetched from USERS TABLE.

     $mod = explode(',',$table_id);
     $mod = array('1','2','3')
     $res = array();

     function addItems($items, $arr) {
        foreach ($items as $value) {
            if (!in_array($value, $arr)) {
                $arr[] = $value;
            }
        }

        return $arr;
     }

     $res = array();
     for ($i = $mod[0]; $i <= end($mod); $i++) {
        $query = $this->db->query("SELECT table_group FROM group where table_id = '$i'");
        $row = $query->row();
        $grp = $row->table_group;
        $group = explode(',', $grp);
        $res = addItems($group, $res);
     }
     return $res;

Its actually working, but the error occuring here is that suppose user selects 1,2,4. In this only the table_group values of 1,2 and 4 must be selected. But with my code, values of 1,2,3,4 are selected. If its 3,4,5 or 2,3,4 etc. then code works just fine. How can i solve this error? Just need to rectify the code.


Solution

  • Change,

    for ($i = $mod[0]; $i <= end($mod); $i++) {
    $query = $this->db->query("SELECT table_group FROM group where table_id = '$i'");
    

    to

    for ($i = 0; $i < count($mod); $i++) {
    $query = $this->db->query("SELECT module_group FROM module_group where module_id = '$mod[$i]'");