简体   繁体   English

如何使用PHP中的第二个元素按字母顺序对数组进行排序

[英]How can I sort arrays alphabetically by using the second element in PHP

Would appreciate any help with this.:) 非常感谢任何帮助。:)

I have the following text file: 我有以下文本文件:

roomA     Springer, Jerry    js@email.com
roomB     Cruise, Tom        tc@email.com
roomC     Jovi, Bon          bj@email.com

and I want to sort it by the surname so it outputs: 我希望按姓氏对其进行排序,以便输出:

Cruise, Tom      roomB        tc@email.com
Jovi, Bon        roomC        bj@email.com
Springer, Jerry  roomA        js@email.com

I know how to load the file: 我知道如何加载文件:

$a = file("details.txt");

and think I have to use explode() to split up the data (tab-seperated): 并认为我必须使用explode()来分割数据(tab-seperated):

$array = explode("\t", $a);

this makes the name the second element in the array. 这使得名称成为数组中的第二个元素。

How do I put the string back together with the name coming first, followed by the room and email? 如何将字符串重新放在一起,首先是名字,然后是房间和电子邮件? Thanks. 谢谢。

Do a var_dump($array) and it will display you the indexes. 执行var_dump($array) ,它会显示索引。 You then only need to swap two elements with each other. 然后,您只需要互相交换两个元素。 Here is a trick: 这是一个技巧:

list($array[0], $array[1]) = array($array[1], $array[0]);

After that, you can implode the result as you did explode it: 之后,您可以在explodeimplode结果:

$line = implode("\t", $array);

Hope this is helpful. 希望这是有帮助的。 Ah well, and for sorting, take a look at array_multisort . 好吧,为了排序,看看array_multisort

PHP不是这项工作的最佳工具。

awk -F"\t" '{print $2"\t"$1"\t"$3}' infile | sort > outfile

your data is not in a know format that i know .. the tabs and space between them are not constant ; 您的数据不是我知道的已知格式..它们之间的tabsspace不是恒定的;

* Do not use in production .. i had to hack my way around * *不要在生产中使用..我不得不破解我的方式*

Try 尝试

$note  = "roomA     Springer, Jerry    js@email.com
roomB     Cruise, Tom        tc@email.com
roomC     Jovi, Bon          bj@email.com";

$data = array();
$info = explode("\n", $note);

echo"<pre>" ;
foreach($info as $line)
{
    $words = preg_split("/\\s/", $line);
    $words = array_filter($words); // remove spaces
    $words = array_values($words); // To reset the keys 
    $data[$words[1] . $words[2]] = $words[1] . $words[2] ."\t" . trim($words[0]) . "\t" . trim($words[3]) .  "\n";
}

asort($data); //Sorting the data ;
print_r(array_values($data));

Output 产量

Array
(
    [0] => Cruise,Tom   roomB   tc@email.com

    [1] => Jovi,Bon roomC   bj@email.com

    [2] => Springer,Jerry   roomA   js@email.com

)

Advice 忠告

Use standard formats suvh as csv , json or xml 使用标准格式如csvjsonxml

I would try improving it with preg_match 我会尝试使用preg_match来改进它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM