<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithHeadings;

class ArrayExport implements FromArray, WithHeadings
{
    protected $rows;
    public function __construct(array $rows)
    {
        $this->rows = $rows;
    }

    public function array(): array
    {
        // if rows are associative, normalize to array-of-arrays
        return $this->rows;
    }

    // optional: if first row is associative, derive headings
    public function headings(): array
    {
        if (isset($this->rows[0]) && is_array($this->rows[0])) {
            $first = $this->rows[0];
            // if numeric keys, no headings desired
            if (array_keys($first) !== range(0, count($first)-1)) {
                return array_keys($first);
            }
        }
        return [];
    }
}