2017-06-21 247 views
0

我有一個CSV文件和前兩列頭閱讀CSV文件到數組並跳過第一行PHP

'Student','ID','SIS User ID' 
Points Possible  
Ashe, 797389, 11721809 
Darius, 20237, 55050811 
Fizz, 34604, 55035088 
Tom Kenn,20232, 55050802 
Vayne, 797413, 11813445 

對於前兩列,他們不應該被添加到陣列中。 從阿什開始,我想Ashe, 797389, 11721809行添加到array[0] 大流士array[1],....

我寫我的代碼如下:

<?php 
$csvData = file_get_contents('output.csv'); 
$lines = explode(PHP_EOL, $csvData); 
$array = array(); 
foreach ($lines as $line) { 
    $array[] = str_getcsv($line); 
} 
print_r($array[2][5]); 
?> 

我應該以跳過做前兩行?

修復問題後,出現一個空數組。如何消除空陣列?

[797413] => Array 
    (
     [0] => Vayne 
     [1] => 797413 
     [2] => 11813445 
     [3] => lsmdec 
     [4] => cs3487 
     [5] => 12.15 
     [6] => 15 
     [7] => 5 
     [8] => 17 
     [9] => 49.15 
     [10] => 49.15 
     [11] => 49.15 
     [12] => 49.15 
     [13] => 49.15 
     [14] => 49.15 
     [15] => 49.15 
     [16] => 49.15 
     [17] => C- 
     [18] => C- 
    ) 

[] => Array 
    (
     [0] => 
    ) 

回答

4

你可以從數組中刪除第一個元素,並保持安全的地方以備以後使用,就像這樣:

<?php 
$csvData = file_get_contents('output.csv'); 
$lines = explode(PHP_EOL, $csvData); 
$array = array(); 
$first_row = array_shift($lines); 
foreach ($lines as $line) { 
    $newLine = str_getcsv($line); 
    if(isset($newLine[0]) && !empty($newLine[0])){ 
     $array[] = str_getcsv($line); 
    } 
} 
print_r($array[2][5]); 

?> 

這將會把你的數組的第一個元素爲$first_row和刪除$lines; 如果您需要跳過超過第一行,您可以堆棧array_shift()方法刪除第一行兩次。

+0

它的作品! Thx爲您提供幫助!它拯救了我的一天! – killer2318

+0

@ killer2318不客氣! – FMashiro

+0

[797413] =>數組 ( [0] => Vayne [1] => 797413 [2] => 11813445 [3] => lsmdec [4] => cs3487 [5] => 12.15 [6] => 15 [7] => 5 [8] => 17 [9] => 49.15 [10] => 49.15 [11] => 49.15 [12] => 49.15 [13] => 49.15 [14] => 49.15 [15] => 49.15 [16] => 49.15 [17] => C- [18] => C-(0)=> ) – killer2318

0
$csvData = file_get_contents('output.csv'); 
    $lines = explode(PHP_EOL, $csvData); 
    $array = array(); 
    foreach ($lines as $key => $line) {    
     if ($key !== 0) { 
      $array[] = str_getcsv($line); 
     } 
    } 
    echo '<pre>'; 
    print_r($array); 
    die; 

現在你可以別的檢查數組值也可以轉移第一陣列可以使用array_shift功能