php - CodeIgniter 向 CSV 添加字段

标签 php mysql codeigniter csv

我在下面有这段代码,它的作用是从数据库中的数据生成 CSV,并且运行良好。我唯一的问题是我想向 CSV 添加另一个字段(如果可能的话,在中间而不是最后)这可能吗?该字段将从数据中获取 DOB,并根据年龄给该人一个头衔(1994 年之后出生,他们是“初级”,在他们是“高级”之后出生)等等,一个年龄可以有 4 到 5 个不同的头衔是。我希望这是有道理的。

function csv_all_members(){

                $this->load->dbutil();
                $this->db->select("first_name as 'First Name', last_name as 'Last Name', phone as 'Phone', os.group as 'Group', gender as 'Gender', birth_date as 'DOB', email as 'Email', street_address as 'Address', city as 'City', province as 'Province', postal_code as 'Postal Code', country 'Country', payment_amount as 'Payment Amount', DATE_FORMAT(payment_date, '%d/%m/%Y') as 'Payment Date', an.notes as 'Notes'", false);
                $this->db->from('offline_shoppers os');
                $this->db->join('athlete_notes an', 'os.id = an.id', 'inner');
                $this->db->group_by(array("first_name", "last_name"));
                $this->db->order_by("last_name asc, first_name asc");
                $query = $this->db->get();
                header("Content-type: text/csv");
                header("Content-Disposition: attachment; filename=members_list.csv");
                header("Pragma: no-cache");
                header("Expires: 0");
                echo $this->dbutil->csv_from_result($query);
        }

最佳答案

只需将其添加到选择语句中即可:

$this->db->select("IF(year(birth_date) > 1994, 'Junior, 'Senior') AS Title "

整体看起来像这样:

$this->db->select("
    first_name as 'First Name',
    last_name as 'Last Name',
    phone as 'Phone',
    IF(year(birth_date) > 1994, 'Junior, 'Senior') AS Title,
    os.group as 'Group',
    gender as 'Gender',
    birth_date as 'DOB',
    email as 'Email',
    street_address as 'Address',
    city as 'City',
    province as 'Province',
    postal_code as 'Postal Code',
    country 'Country',
    payment_amount as 'Payment Amount',
    DATE_FORMAT(payment_date, '%d/%m/%Y') as 'Payment Date',
    an.notes as 'Notes'");

编辑:对于“else if”情况使用:

    (
    CASE 
        WHEN year(birth_date) > 1994 THEN 'Junior'
        WHEN year(birth_date) > 2000 THEN 'Jr. Junior'
        WHEN year(birth_date) > 2012 THEN 'Jr. Jr. Junior'
        ELSE 'Senior'
    END) AS Title

关于php - CodeIgniter 向 CSV 添加字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18706748/

相关文章:

php - 当天的项目

php - 使用破折号引起的未定义常量?

php - 使用 PSR-4 找不到类

Java JDBC MySQL异常: “Operation not allowed after ResultSet closed”

php - 如何通过 SQL 将一系列值添加到我的数据库中?

javascript - 如何通过单击按钮关闭 jQuery fancybox

php - 如何在变量中存储选择选项 onchange 并将其作为参数传递到单个 php 页面

php - 插入查询-存储时间

php - Codeigniter:常用函数。与多个功能。数据库查询性能

php - 如何在 Codeigniter 中将事件 session ID 解析为外键