CodeIgniter 向 CSV 添加一个字段
Posted
技术标签:
【中文标题】CodeIgniter 向 CSV 添加一个字段【英文标题】:CodeIgniter adding a field to CSV 【发布时间】:2013-09-13 10:40:23 【问题描述】:我在下面有这段代码,它的作用是从数据库中的数据生成一个 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);
【问题讨论】:
【参考方案1】:只需将其添加到 select 语句中:
$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
【讨论】:
如果也可以使用 else 吗?因为我需要做 4 或 5 次比较以上是关于CodeIgniter 向 CSV 添加一个字段的主要内容,如果未能解决你的问题,请参考以下文章
从codeigniter中的数据库查询向视图添加动态数据时未定义的变量[重复]