第一部分代码工作正常,但第二部分(显示结果)工作错误。如果我在$slugs = explode(',', $slugs)
内插入foreach ($pma...)
,则会出现explode() expects parameter 2 to be string, array given
错误。如果我现在保持它,它可以工作,但结果以“马赛克,散乱”模式给出,具有多个相同的结果。即使print_r()
每行显示800个结果(这是无意义的)。
如何解决这个问题?
$data = fopen('php://output', 'w');
$fields = rtrim($_GET['fieldnames'], ",");
$slugs = rtrim($_GET['slugs'], ",");
$fieldnames = array();
$fieldslugs = array();
$pma = DB::table... // long query
$fields = explode(',', $fields);
foreach ($fields as $field) {
$fieldnames[] = $field;
}
fputcsv($data, $fieldnames);
$slugs = explode(',', $slugs);
foreach ($pma as $p) {
foreach ($slugs as $slug) {
$fieldslugs[] = $p->$slug;
}
fputcsv($data, $fieldslugs);
}
对不起英语不好,坦克得到答案!
答案 0 :(得分:1)
您需要在foreach前面添加$fieldslugs = [];
$fieldslugs = [];
foreach ($slugs as $slug) {
$fieldslugs[] = $p->$slug;
}
fputcsv($data, $fieldslugs);
答案 1 :(得分:1)
试试这个:
foreach ($pma as $p) {
$fieldslugs = [];
foreach ($slugs as $slug) {
$fieldslugs[] = $p->$slug;
}
fputcsv($data, $fieldslugs);
}
您需要为每次迭代重置数组,否则它将继续填充相同的数组,从而将新行结果附加到每个csv行。