2014-09-01 79 views
-1

您好我有需要過濾的CSV文件,從A-C,d-F等過濾CSV使用PHP

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和我試圖通過下面這樣的代碼來修復它。

<?php 
$file = fopen('LoggedInUsers.csv', 'r'); 

$first = array('Aaron'); 
$last = array('Carlos'); 



while (($line = fgetcsv($file)) !== FALSE) { 
    list($name, $log, $department) = $line; 

    $firstt = array('Aaron'); 
    if ($first < 0) { 
    } 
    $last = array ('Carlos'); 
    if ($last < 0) { 
} 
?> 
+0

你想幹什麼過濾或修復?這是關於排序嗎?你打算用「$ first」和「$ last」做什麼? – mario 2014-09-01 03:22:40

回答

0

我會做的是創建一個僞分組結構第一個(數組)A-C, D-F, ...將用於分組,然後只檢查迭代當前的第一個字母,然後根據其屬於的格式推入它。例如:

$filters = array_chunk(range('a', 'z'), 3); // grouping structure 
$file = fopen('LoggedInUsers.csv', 'r'); 

$data = array(); 
while (($line = fgetcsv($file)) !== false) { 
    list($name, $log, $department) = $line; 
    foreach($filters as $batch =>$filter_batch) { 
     // if the current name does belong to this structure, push it inside 
     if(in_array(strtolower(substr($name, 0, 1)), $filter_batch)) { 
      $data[$batch][] = $name; 
     } 
    } 
} 

echo '<pre>'; 
print_r($data); 

所以輸出應該是:

Array 
(
    [0] => Array // batch of A-C 
    (
     [0] => Aaron 
     [1] => Arianne 
     [2] => Bea 
     [3] => Carlos 
    ) 

    [1] => Array // batch of D-F 
    (
     [0] => Drake 
     [1] => Delilah 
     [2] => Erica 
     [3] => Flint 
    ) 

) 
1

您可以使用substr從您的字符串獲得一個特定的字符,但有一個叫strncasecmp

首先的字符串的第一個n字符比較具體的方法,可以保證記錄在CSV中按字母順序排序?我假設不是這樣,我們將遍歷每一行並將匹配的行添加到數組;

$first = "A"; 
$last = "C"; 

$Ret = array(); 

while (($line = fgetcsv($file)) !== FALSE) { 
    list($name, $log, $department) = $line; 

    if (strncasecmp($name, $first, 1) >= 0 && strncasecmp($name, $last, 1) <= 0) { 
     array_push($Ret, array($name, $log, $department)); 
    } 
} 

//Show what we got 
print_r($Ret); 

運行此之後,$Ret應該包含所有的名字開始與$first字母$last(含)

這樣做的好處是,你不需要知道具體的名字,只是字母您有興趣。

請注意,strncasecmp用於不區分大小寫的字符串比較。基本上,如果字符串的第一個字符相等,則返回0;如果第一個字符串在第二個字符的「之前」,則返回負值;如果是「之後」,則返回正值。

0
/** 
* Function to sort multidimensional array on first element using 
* PHP's usort(). 
* @see http://uk1.php.net/manual/en/function.usort.php 
**/ 
function username_sort($foo, $bar){ 
    return ($foo[0] > $bar[0]); 
} 

// Gets all file content into a multidimensional array in memory 
$loggedInUsers = array_map('str_getcsv', file('LoggedInUsers.csv')); 

// Sorts the array by the first element (username) in a copy of the data. 
$sorted_loggedInUsers = usort($loggedInUsers, 'username_sort'); 

此時你有一個排序的數組中的數據,是array_slice() d無論你想這樣做。