仅使用foreach限制显示值的字段

时间:2016-05-14 06:09:27

标签: php codeigniter

我有数据库结构

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

每个礼品列的值为1或0。 进行搜索时,我需要显示值不等于零的字段(值!= 0)。 我知道我可以在VIEW中执行此操作

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

但是我需要它以限制自动化。

我的MODEL代码是

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;
}

请帮忙

2 个答案:

答案 0 :(得分:1)

在选择之前将“DISTINCT”关键字添加到查询中,以获取唯一记录

$this->db->distinct();

希望它可以帮到你!

答案 1 :(得分:0)

您只需使用自定义数组构建

删除空列
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 
}