简体   繁体   中英

Iterate elements inside foreach loop in laravel

I want to iterate through a nested array

        $row = 7;
        $i = 0;
        foreach($studentsInfo as $data) {
                $spreadsheet->getActiveSheet()
                ->setCellValue('A' . $row, $data[$i]);
                $row++;
                $i++;
        }

but the error came up.

I tried to use the "for" loop inside my "foreach" loop but the data is duplicated.

        $row = 7;
        foreach($studentsInfo as $data) {
            $studentLength = count($data);
            for ($i = 0; $i < $studentLength; $i++) {
                $spreadsheet->getActiveSheet()
                ->setCellValue('D' . $row, $data[$i]);
                $row++;
            }
        }

Here's the structure of the array

How can I avoid this error?

If you have this code:

$row = 7;
$i = 0;
foreach($studentsInfo as $data) {
        $spreadsheet->getActiveSheet()
        ->setCellValue('A' . $row, $data[$i]);
        $row++;
        $i++;
}

You take for granted that $data would would contain indexes like

[0] item1
[1] item2
[2] item3
[3] item4

etc.

When you do not actually know the key you should it like this when using foreach :

$row = 7;
foreach($studentsInfo as $data) {
    $spreadsheet->getActiveSheet()
    ->setCellValue('A' . $row, $data);
    $row++;
}

if it's just the value your interested in for each item in the array ( $data )

If you have an array in array then just do a foreach-loop inside:

foreach($studentsInfo as $data) {
    foreach($data as $actual_value) {
        $spreadsheet->getActiveSheet()
        ->setCellValue('D' . $row, $actual_value);
        $row++;
    }
}

I hope you get "the picture" how you should move on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM