laravel chunk忽略了迭代器

I know this will end up being obvious, but the below method inserts my array_keys multiple times. I've attempted to use a counter before the chunk method and doing a (use) to bring it in and increment after the first time it uses it. The method simply ignores it. Is there a smart way to use chunk and only insert array_keys one time?

$resultMain->chunk(2000, function ($portion) {
    {
        $fh = fopen('php://output', 'w');
        $heading = false;
        if (!empty($portion))
            foreach ($portion as $row) {
                $row = json_decode(json_encode($row), true);
                if (!$heading) {
                    // output the column headings
                    fputcsv($fh, array_keys($row));
                    $heading = true;
                }
                // loop over the rows, outputting them
                fputcsv($fh, array_values($row));
            }
    }
});
fclose($fh);

}

this seems stupid but I can't make laravel let me get at the first col any other way (this is a huge result set) -- if anyone can think of a less weird way to do this I would be all ears:

 $header = $resultMain->take(1)->get();
   foreach ($header as $row) {
      $row = json_decode(json_encode($row), true);
      $fh = fopen('php://output', 'w');
      fputcsv($fh, array_keys($row));
   }

$resultMain->chunk(2000, function ($portion){
    {
        $fh = fopen('php://output', 'w');
        if (!empty($portion))
            foreach ($portion as $row) {
                $row = json_decode(json_encode($row), true);
                // loop over the rows, outputting them
                fputcsv($fh, array_values($row));
            }
    }
});
fclose($fh);

}