Sebastian Sebastian - 6 months ago 13
PHP Question

Displaying fields with values only with foreach limit

I have db structure

id | ref_id | amenity1 | amenity2 | amenity3 | amenity4 | amenity5

Each amenity column has values 1 or 0.
When a search is made, I need to display the field that has values not equals to zero (value != 0).
I know I can do this in VIEW as

if($data->amenity1 == 0) echo '';


But I need it to be automated with limit.

My code for MODEL is

function select_all_active_amenities($for_id){
foreach($for_id as $id){
$prop_id = $id->vbc_item_id;
}
$this->db->select('*');
$this->db->from('vbc_property_amenities');
$this->db->where_in(array('v_ref_id'=> $prop_id));
$this->db->limit(5);
$query = $this->db->get();
$result = $query->result();

return $result;
}


Please help

Answer

you just remove empty column using custom array build

function select_all_active_amenities($for_id){
foreach($for_id as $id){
    $prop_id = $id->vbc_item_id;
}
$this->db->select('*');
$this->db->distinct('v_ref_id');
$this->db->from('vbc_property_amenities');
$this->db->where_in(array('v_ref_id'=> $prop_id));
// $this->db->limit(5);
 $query = $this->db->get();
 $result1 = $query->result_array();

 //fetch the value as array 

//and this query for fetch the column name what you have right now an where not equal to id and ref_id

 $this->db->query("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='vbc_property_amenities' AND COLUMN_NAME !='id' AND COLUMN_NAME != 'ref_id AND COLUMN_NAME !='id' ")->result_array();
  $query = $this->db->get();
  $result2 = $query->result_array();

foreach($result as $key1=>$row1)
{

        foreach($result2 as $key2=>$row2)
        {

            if($row2 ==$row1[$row2] && $row1 ==0)
            {

                unset($result[$key1][$row2]);
            }

        }



}

//$result only have the where value=1 

return $result;

//you just limit the five in your view page 
}