2016-12-15 57 views
0

因此,我正在製作一個表單,我想讓用戶選擇上傳一個允許表單自動填充的CSV。所以我認爲我會構建一個讀取CSV的函數,然後將每行作爲一個對象拋入一個數組中,然後我可以將其傳回到我的Laravel Blade模板。我唯一的問題是,我從函數返回的數組總是空的。有任何想法嗎?Laravel Excel:CSV到數組

private function import($path) { 
    $applicants = []; 

    Excel::load($path, function(LaravelExcelReader $excel) use ($applicants){ 
     $excel->each(function(Collection $line) use ($applicants){  
      $name = new \stdClass;  

      $name->first = $line->get('first'); 
      $name->middle = $line->get('middle'); 
      $name->last = $line->get('last'); 
      $name->birthdate = $line->get('birthdate'); 
      $name->ssn = $line->get('ssn'); 
      $name->email = $line->get('email'); 
      $name->mobile_phone = $line->get('mobile_phone'); 
      $name->home_phone = $line->get('home_phone'); 
      $name->street = $line->get('street'); 
      $name->city = $line->get('city'); 
      $name->state = $line->get('state'); 
      $name->zip = $line->get('zip'); 

      array_push($applicants, $name); 
     }); 
    });  

    return $applicants; 
} 

回答

2

use語句中使用&操作員嘗試:

Excel::load($path, function(LaravelExcelReader $excel) use (&$applicants){ 
    ... 
} 

OR

$applicants類屬性然後用它在你的函數爲:

private function import($path) { 
    $this->applicants = []; 

    Excel::load($path, function(LaravelExcelReader $excel) { 
     $excel->each(function(Collection $line) {  
      ... 

      array_push($this->applicants, $name); 
     }); 
    });  

    return $this->applicants; 
} 
1

安裝 - https://github.com/Maatwebsite/Laravel-Excel

,然後嘗試下面的代碼:

$reader = \Excel::load($file_path);     //this will load file 
$results = $reader->noHeading()->get()->toArray(); //this will convert file to array 
foreach($results as $v){ 
    \\process your array 
} 
0

,而不是

array_push($applicants, $name); 

試試這個

$applicants[] = $name; 

讓我知道,如果它