Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/245.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Codeigniter选择distinct并传递变量列表_Php_Mysql_Codeigniter - Fatal编程技术网

Php Codeigniter选择distinct并传递变量列表

Php Codeigniter选择distinct并传递变量列表,php,mysql,codeigniter,Php,Mysql,Codeigniter,只想从表中选择DISTINCT country,其中user_id=$user_id,将国家列表从模型传递给控制器,然后传递国家列表的JSON表示,但由于我是Codeigniter的新手,我不确定是否正确编写了查询,是否返回了列表或单个值。你能查一下我的密码吗 型号: public function did_get_country_list($user_id) { $this->db->distinct('country'); $this->d

只想从表中选择DISTINCT country,其中user_id=$user_id,将国家列表从模型传递给控制器,然后传递国家列表的JSON表示,但由于我是Codeigniter的新手,我不确定是否正确编写了查询,是否返回了列表或单个值。你能查一下我的密码吗

型号:

public function did_get_country_list($user_id) {

        $this->db->distinct('country');
        $this->db->where('user_id',$user_id);
        $query = $this->db->get('table');

        if ($query->num_rows() >= 1) {
         foreach ($query->result() as $row)
        {
            $country = $row->country;
        }
        return $country;
        }
        else{
         return false;
        }       
    }   
控制器:

$country = $this->model_users->did_get_country_plans($user_id);

echo json_encode($country);

您的代码在我看来几乎没问题,但我认为您应该更改两行:

1) 在实际查询之前删除对num_行的检查

2) 要返回国家/地区数组,请在
$country
末尾添加
[]
以推送新值

因此,与其说是这个片段,不如说是:

    if ($query->num_rows() >= 1) {
     foreach ($query->result() as $row)
    {
        $country = $row->country;
    }
    return $country;
    }
    else{
     return false;
    }
你应该:

    $country = false;
    foreach ($query->result() as $row)
    {
        $country[] = $row->country;
    }
    return $country;

谢谢你的回答。我不明白为什么要删除对num_行的检查。好吧,实际上你可以保留它(我的第一个答案只是修改数组),但是删除它我认为会让你的代码更短…谢谢!这部分代码的编写目的是什么$国家=假;这是为了返回
false
如果您没有在
foreach
循环中输入,那么无论如何,您可以保留
($query->num_rows()>=1)
逻辑。。。也许你不应该把它去掉:p