我有一个变量,它从数据库中保存我的数组,它们是名称和电子邮件地址。
数组结构是:
Array (
[0] => stdClass Object ( [fname] => FName [lname] => LName [email] => Email )
[1] => stdClass Object ( [fname] => FName [lname] => LName [email] => Email )
)
等等通过所有用户列表
我已经在框架中创建了csv文件的所有设置,我只是在构建foreach循环以迭代数组变量并将该信息放入csv时遇到问题。我尝试了几种不同的方法,我只是将错误加载到csv中。我已经有了标题。
$users = SiteUser::select()->getColumns('fname, lname, email');
foreach ($users as $u) {
// print each user as a CSV row (columns are name, email)
// Anything here will be place into the csv file for download
}
exit;
}
答案 0 :(得分:0)
您可以将stdClass
转换为数组,然后使用fputcsv
输出:
// Get pointer to standard output
$fp = fopen('php://output', 'w');
// write column headers
fputcsv($fp, ["name", "email"]);
foreach ($users as $u) {
// assemble array and write
fputcsv($fp, [$u->fname . " " . $u->lname, $u->email]);
}
fclose($fp);