-1

I have a text file called base.txt with the following contents (using : as the delimiter to separate the form data):

jon:doe:fakeemail@mail.com:fakepassword
bob:cosper:bob2@mail.com:fakepass

In the php file I made that into an array by doing:

$data = file('base.txt');

Now if I want to print the contents and sort it by the first name I just dosort($data); but what can I do if I wanted to sort it by the last names or the emails?

1 Answers1

0

You can use your own function to order the array with usort() and use strnatcasecmp() to compare the strings by natural order algorithm, like this:

function sortbyPos(&$array, $delimiter, $pos = 0) {
    usort($array, function($a, $b) use($delimiter, $pos) {
        $a = explode($delimiter, $a);
        $b = explode($delimiter, $b);
        return strnatcasecmp($a[$pos], $b[$pos]);
    });
}

I put the parameters like delimiter and position to choose the value in the string that you have, this are the results:

The data:

$data = [
    'jon:doe:fakeemail@mail.com:fakepassword',
    'ross:geller:anothermail@mail.com:fakepass2',
    'bob:cosper:bob2@mail.com:fakepass'
];

Order by last name (1 position in the string because is an array):

sortbyPos($data, ':', 1);
print_r($data);

Results:

Array
(
    [0] => bob:cosper:bob2@mail.com:fakepass
    [1] => jon:doe:fakeemail@mail.com:fakepassword
    [2] => ross:geller:anothermail@mail.com:fakepass2
)

Order by email:

sortbyPos($data, ':', 2);
print_r($data);

Results:

Array
(
    [0] => ross:geller:anothermail@mail.com:fakepass2
    [1] => bob:cosper:bob2@mail.com:fakepass
    [2] => jon:doe:fakeemail@mail.com:fakepassword
)
kip
  • 1,120
  • 7
  • 11