dongpo1846 2014-09-01 03:17
浏览 55
已采纳

使用PHP过滤CSV

Hi I have a CSV file that needs filtering, from A-C, D-F and so on

    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

Im not good at PHP and I tried to fix it by doing this code below.

<?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) {
}
?>
  • 写回答

3条回答 默认 最新

  • doukanmang3687 2014-09-01 04:54
    关注

    What I would do is create a pseudo grouping structure first (an array) A-C, D-F, ... that would be used for grouping, then just check the current first letter on the iteration, then just push it inside according to its belonged format. Example:

    $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);
    

    So the output should be:

    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
        )
    
    ) 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,