0
votes

I would like to export Excel in Laravel version 5.7. I am using package Maatwebsite Laravel Excel version 3.1. I have an array of persons' information like this:

 $persons = {
        "person 1": [
            {
                "answer1": "shokouh"
            },
            {
                "answer2": "dareshiri"
            },
            {
                "answerN": "answer N"
            }
        ],
...
        "person M ": [
            {
                "answer1": "sarah"
            },
            {
                "answer2": "smith"
            },
            {
                "answerN": "answer N"
            }
        ]
    }

and I wanna to export that in such as below excel:

Person 1    Answer 1    Answer 2    …   Answer N
Person M    Answer M2   Answer M2   …   Answer MN

This is my export function in Controller:

public function export(Request $request, Tournament $tournament) {

    ... 

    $persons;

    return Excel::download(new ParticipantExport($persons), 'personInformation.xlsx');
}

This is my participantExport in app\Export\participantExport:

class participantExport implements FromArray
{
    protected $invoices;

    public function __construct(array $invoices)
    {
        $this->invoices = $invoices;
    }

    public function array(): array
    {
        return $this->invoices;
    }
}

any body can help me?

1

1 Answers

0
votes

I solved the question as below:

In Controller.php:

$rows = array();

        foreach ($persons as $slug => $person) {
            $row = array();
            array_push($row, $slug);
            foreach ($person as $key => $value) {

                array_push($row, $persons[$slug][$key]['answer']);

            }
            array_push($rows, $row);
        }

        $coll = new participantExport([$rows]);


        return Excel::download($coll, 'participant-information.xlsx');