Search code examples
phparrayslaravelfputcsv

Creating CSV file using data from database, gives "mosaic, straggly" results


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!


Solution

  • 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.