用PHP姓氏排序CSV文件 [英] Sort a CSV file by last name with PHP

查看:382
本文介绍了用PHP姓氏排序CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将如何使用PHP排序我下面的CSV文件?我想按姓氏排序。难道我用正则表达式以某种方式获得姓氏的第一个字母?任何帮助AP preciated

下面是我的CSV文件的摘录 - 用;名称与地址之间的分隔符

 约翰·巴克利,医学博士; 123主街,马里兰州贝塞斯达20816
史蒂芬P.木; 345榆树街,马里兰州洛克维尔20808
理查德·E.巴尔 - 费尔南德斯; 234松树街,塔科马公园MD 20820
查尔斯·鲍威尔安德鲁; 678橡树街,盖瑟斯堡MD 20800
马克·大卫·霍洛维茨,三; 987华尔街,银泉MD 20856


解决方案

下面是我的尝试。我不知道正则表达式是多么健壮,虽然提取姓。

 < PHP
$处理=的fopen('C:/csv.txt','R')或死亡(无法读取文件');
$姓氏=阵列();
$行=阵列();//建立姓氏的数组,行阵
而(假=($行= fgetcsv($处理,0';'))){
    //从第一塔中提取姓
    //这应该逗号之前的最后一个字相匹配,如果有一个逗号
    preg_match('?。?〜([^ \\ S] +)(:*)$〜',$行[0],$ M);
    $姓氏[] = $ M [1];
    $行[] = $行;
}FCLOSE($处理);使用我们的姓氏排列的行//数组排序按姓氏
在array_multisort($姓氏,$行);的print_r($行);
//你可以写$行回文件在这里,如果你想要的。

修改

我才意识到,你不真的需要剥去人民的后缀,因为这可能不会真正影响排序。你可以只在空间分割的第一列,并采取最后一个(如karim79建议)。这可能会破坏但如果这个人有多个后缀带有空格的,所以我会离开我的答案不变。

How would I sort the following CSV file using PHP? I would like to sort by last name. Do I use regex somehow to get the first letter in the last name? Any help is appreciated

Here is an excerpt of my CSV file - with a ";" delimiter between names and addresses

John C. Buckley, M.D.;123 Main Street, Bethesda MD 20816
Steven P. Wood;345 Elm Street, Rockville, MD 20808
Richard E. Barr-Fernandez;234 Pine Street, Takoma Park MD 20820
Charles Andrew Powell; 678 Oak Street, Gaithersburg MD 20800
Mark David Horowitz, III; 987 Wall Street, Silver Spring MD 20856

解决方案

Here is my attempt. I'm not sure how robust the regex is to extract the surname though.

<?php
$handle = fopen('c:/csv.txt', 'r') or die('cannot read file');
$surnames = array();
$rows = array();

//build array of surnames, and array of rows
while (false != ( $row = fgetcsv($handle, 0, ';') )) {
    //extract surname from the first column
    //this should match the last word before the comma, if there is a comma
    preg_match('~([^\s]+)(?:,.*)?$~', $row[0], $m);
    $surnames[] = $m[1];
    $rows[] = $row;
}

fclose($handle);

//sort array of rows by surname using our array of surnames
array_multisort($surnames, $rows);

print_r($rows);
//you could write $rows back to a file here if you wanted.

Edit

I just realised that you don't really need to strip off the peoples' suffixes, because this probably won't really affect sorting. You could just split the first column on space and take the last one (as karim79 suggested). This might break though if the person has more suffixes with spaces, so I'll leave my answer intact.

这篇关于用PHP姓氏排序CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆