php - 在 codeigniter 中使用 foreach 循环获取单个值

标签 php mysql codeigniter

tbl_产品:

+------------+--------------+-------------+------------+
| product_id | product_name | category_id |company_name|
+------------------------------------------------------+
| 1          | iPhone       |      3      |  Apple     |
| 2          | galaxy s1    |      3      |  Samsung   |
| 3          | galaxy s2    |      3      |  Samsung   | 
| 4          | tab          |      4      |  Apple     |
+------------------------------------------------------+

从上表中,我想根据category_id获取公司名称。我已经使用 foreach 来获取值。我买过三星两次,苹果一次。但我希望三星和苹果都只展示一次。是否可以?我在我的模型中编写了以下代码。

    public function select_company_by_category_id($category_id) {
    $this->db->select('*');
    $this->db->from('tbl_products');
    $this->db->where('category_id', $category_id);
    $query_result = $this->db->get();
    $result = $query_result->result();
    return $result;
}

最佳答案

使用group_by,并仅选择company_name:

public function select_company_by_category_id($category_id) {
    $this->db->select('company_name');
    $this->db->from('tbl_products');
    $this->db->where('category_id', $category_id);
    $this->db->group_by('company_name');
    $query_result = $this->db->get();
    $result = $query_result->result();
    return $result;
}

关于php - 在 codeigniter 中使用 foreach 循环获取单个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35132902/

相关文章:

php - 使用 PHP 创建数组

php - 从随机 PHP 整数填充 SQL 中一列的所有行

php - 不同服务器上相同数据的 SimpleXML 差异

mysql - LOAD DATA INFILE 仅加载 0、NULL 和空白

php - 如何在 php 中构建具有 id、parent_id 和深度变量的树

php - 如何在 PHP 中按行长度限制文本?

php - 将表单数据保存在 url 中,无需重新加载页面

php - MYSQL/查询生成器/Eloquent - 将行转置为列

java - 如何从 unix 时间戳中提取小时数?

php - 如何配置Codeigniter报告所有错误?