2014-08-28 38 views
1

我在這裏是新的,我想獲得CSV的特定行,但實際上無法得到它,希望有人可以幫助我。CSV顯示特定行

以下是我的CSV示例。

Aaron, Male, [email protected] 
Arianne, Female, [email protected] 
Bea, Female, [email protected] 
Carlos, Male, [email protected] 
Drake, Male, [email protected] 
Delilah, Female, [email protected] 
Erica, Female, [email protected] 
Flint, Male, [email protected] 

我想只在我的文件中顯示從德雷克到艾瑞卡的一行。

這裏是我的代碼

<?php 
echo "<html><body><table BORDER=1, WIDTH=1200px>\n\n"; 
$f = fopen("Senter code hereample.csv", "r"); 
while (($line = fgetcsv($f)) !== false){ 
     echo "<tr>"; 
     foreach ($line as $cell) { 
       echo "<td>" . htmlspecialchars($cell) . "</td>"; 
     } 
     echo "</tr>\n"; 
}`enter code here 
fclose($f); 


echo "\n</table></body></html>"; 
?> 
+0

單行:'$ line [number_here]'。 – PHPglue 2014-08-28 02:10:12

+0

需要一個數組去除引用(假設PHP 5.4+)調用'fgetcsv($ f)[number_here]'。 '$ line'只是循環中的一個指針。 – 2014-08-28 02:19:23

回答

1
<?php 
echo "<html><body><table BORDER=1, WIDTH=1200px>\n\n"; 
$f = fopen("file.csv", "r"); 
$i = 0; 
while (($line = fgetcsv($f)) !== false){ 
    $i ++; 
    echo "<tr>"; 

    foreach ($line as $cell) { 
     if ($i==5 ||$i==6||$i==7) 
     echo "<td>".$i.' - '. htmlspecialchars($cell) . "</td>"; 
    } 
    echo "</tr>\n"; 
} 
fclose($f); 
echo "\n</table></body></html>"; 
?> 

測試和工作樣本。

+0

應該用'count()'代替'for'循環。它的工作原理是 – PHPglue 2014-08-28 02:11:31

+0

。謝謝! :) – jcarlos 2014-08-28 02:31:13

+0

如果我添加了另一列,讓我們說「brock,male,[email protected]」,數字5將carlos和7將delilah – jcarlos 2014-08-28 07:43:17

1

在要顯示德雷克,大利拉和Erica你可以這樣做這個具體的例子:

$csv_lines = file('yourcsv.csv'); 

echo $csv_lines[4]; // Drake, Male, [email protected] 
echo $csv_lines[5]; // Delilah, Female, [email protected] 
echo $csv_lines[6]; // Erica, Female, [email protected] 

如果CSV是動態的,你要搜索的,而不是通過參考它們對這些名稱的確切的行號,這可能是一個更好的方式來做到這一點,你可以做這樣的事情:

$csv_lines = file('yourcsv.csv'); 

// Filter out anything that isn't the right first name 
$csv_lines = array_filter($csv_lines, function($value) { 
    /// Split up the line and trim each result 
    $line_bits = array_map('trim', explode(',', $value)); 
    // If the first name is in your array, return this value otherwise strip it 
    return in_array($line_bits[0], array('Drake', 'Delilah', 'Erica')); 
}); 

數組的轉儲然後返回:

Array 
(
    [4] => Drake, Male, [email protected] 
    [5] => Delilah, Female, [email protected] 
    [6] => Erica, Female, [email protected] 
) 

注:使用file()是文件讀入一個數組一個快速簡便的方法,但作爲整個文件需要被加載到內存它可以被解析之前,不應該使用,如果你的文件大。在這種情況下,它是合適的,但應該逐行處理大量文件。

Here's a demo這兩個例子。 (注:file()在本例中用新行代替explode())。

+0

是的,謝謝。我需要睡覺))) – voodoo417 2014-08-28 02:25:23