您好我有一个需要过滤的CSV文件,来自A-C,D-F等
Aaron, Male, aaron@website.com
Arianne, Female, arianne@something.com
Bea, Female, bea@hello.com
Carlos, Male, carlos@website.com
Drake, Male, drake@website.com
Delilah, Female, del@hello.com
Erica, Female, erika@webisite.com
Flint, Male, flint@something.com
我不擅长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 :(得分: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
字符相等则返回n
,如果第一个字符串是&#34,则返回负值{#1}。第二个,如果它是&#34;在&#34;之后是正值。
答案 1 :(得分: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()。
答案 2 :(得分: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
)
)