简体   繁体   中英

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):

$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. 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:

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

Hope this is helpful. Ah well, and for sorting, take a look at 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 ;

* 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

I would try improving it with preg_match

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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