我在下面有这段代码,它的作用是从数据库中的数据生成 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/