Zeontope
Zeontope

Reputation: 39

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    [email protected]
roomB     Cruise, Tom        [email protected]
roomC     Jovi, Bon          [email protected]

and I want to sort it by the surname so it outputs:

Cruise, Tom      roomB        [email protected]
Jovi, Bon        roomC        [email protected]
Springer, Jerry  roomA        [email protected]

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.

Upvotes: 0

Views: 410

Answers (3)

Baba
Baba

Reputation: 95121

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    [email protected]
roomB     Cruise, Tom        [email protected]
roomC     Jovi, Bon          [email protected]";

$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   [email protected]

    [1] => Jovi,Bon roomC   [email protected]

    [2] => Springer,Jerry   roomA   [email protected]

)

Advice

Use standard formats suvh as csv, json or xml

I would try improving it with preg_match

Upvotes: 0

000
000

Reputation: 27247

PHP isn't the best tool for this job.

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

Upvotes: 0

hakre
hakre

Reputation: 197787

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.

Upvotes: 2

Related Questions