Search code examples
excellaravelfor-loopforeach

I want to get the values of the rows in excel using laravel but it keeps repeating


I imported excel on my laravel application and I extracted the data which I want to loop through row and get the values. I am getting the values but it keeps repeating

public function bulkTransfer(Request $request)
{
    Log::info("########## Validating File #########");

    $request->validate([
        "file" => 'required|file|mimes:csv,xlsx'
    ],[
        "fileName.mimes" => "File should be a csv or excel file"
    ]);
    Log::info("########## File Validated #########");

    if($request->has("file")){
        $allAccounts = Excel::toArray(new \stdClass(), $request->file("file"));
        foreach ($allAccounts as $accounts){
            foreach ($accounts as $account){
              for ($i=0; $i<=count($account); $i++){
                  echo '<p>'.  $account[1] . " " . $account[2] . " " . $account[3] . "</p>";
              }
            }

        }
    }
}

The is the array of data that I got from the excel file

array:1 [ // app/Http/Controllers/TransferController.php:33
  0 => array:4 [
    0 => array:4 [
      0 => "Account Name"
      1 => "Account Number"
      2 => "Bank Code"
      3 => "Amount"
    ]
    1 => array:4 [
      0 => "Okafor John"
      1 => 98393
      2 => 988
      3 => 3000
    ]
    2 => array:4 [
      0 => "Joy Ema"
      1 => 87383
      2 => 8378
      3 => 2000
    ]
    3 => array:4 [
      0 => "Ike Sam"
      1 => 89382
      2 => 888
      3 => 1500
    ]
  ]
]

When I run my code this is the output that I get

Account Number Bank Code Amount

Account Number Bank Code Amount

Account Number Bank Code Amount

Account Number Bank Code Amount

Account Number Bank Code Amount

98393 988 3000

98393 988 3000

98393 988 3000

98393 988 3000

98393 988 3000

87383 8378 2000

87383 8378 2000

87383 8378 2000

87383 8378 2000

87383 8378 2000

89382 888 1500

89382 888 1500

89382 888 1500

89382 888 1500

89382 888 1500


Solution

  • you can show item like this:

          if ($request->has("file")) {
            $allAccounts = Excel::toArray(new \stdClass(), $request->file("file"));
            foreach ($allAccounts as $accounts) {
                foreach ($accounts as $account) {
    
                    //your code : 
                    echo '<p>' . $account[1] . " " . $account[2] . " " . $account[3] . "</p>";
    
                    // better way
                    echo sprintf('<p> %s %s %s %s </p>', $account[0], $account[1], $account[2], $account[3]);
    
                    // php 8.2
                    echo sprintf('<p> %s %s %s %s </p>', ...$account);
                }
    
            }
        }
    

    check this code