使用数据库中的数据创建CSV文件,给出“马赛克,散乱”的结果

First part of code works fine, but the second one (displaying results), works wrongly. If i am inserting $slugs = explode(',', $slugs) inside foreach ($pma...), it gives me explode() expects parameter 2 to be string, array given error. If i keep it as it now, it works, but the results is given in "mosaic, straggly" mode, with multiple same results. Even print_r() shows 800 results per one row (it is nonsense).

How to fix this?

$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);

}

Sorry for bad english, and tanks for any answers!

Try this:

foreach ($pma as $p) {
  $fieldslugs = [];
  foreach ($slugs as $slug) {
    $fieldslugs[] = $p->$slug;
  }

  fputcsv($data, $fieldslugs);

}

You need to reset the array for each iteration, otherwise it will keep filling the same array, and thus appending the new row results to each csv row.

You need to add $fieldslugs = []; in front of foreach

$fieldslugs = [];
foreach ($slugs as $slug) { 
    $fieldslugs[] = $p->$slug;
}

fputcsv($data, $fieldslugs);