Jump to content

Sorting list in PHP


brodinski

Recommended Posts

Hi!

 

I have this problem that I have to solve in PHP. I have such a difficult with this programming and I would be so grateful if someone could help me solve this.

The problem:

A lecturer has a group of students who need to be assigned to one of two groups for the
purpose of workshop sessions. She has a CSV file containing all the student records in the
following form:
 
student number, student first name, student last name
 
and requires that the students in this file are split into two equal sized groups based on the
alphabetical order of their last names. These two groups should be written out into separate
files in the alphabetical order of their last name.
 
I attach the student list in the post (students.txt)
 
If someone could spend their precious time helping me I would be forever thankful!

students.txt

Link to comment
Share on other sites

In the manual page for str_getcsv, it provides an excellent example of how to get started; in the first comment.

 

$csv array_map('str_getcsv'file('data.csv'));

 

You will then have an array with all of the names

 

Also, in the manual, for the function array_multisort, there is another example.

 

foreach ($csv as $key => $row$lnames[$key]  = $row[2];
array_multisort($lnamesSORT_DESC);

 

 

With their powers combined, you can create this

$csv = array_map('str_getcsv', file('csv.csv'));
foreach ($csv as $key => $row) $lnames[$key]  = strtolower($row[2]);
array_multisort($lnames, SORT_ASC, $csv);
echo "<pre>", print_r($csv), "</pre>";

$csv is now sorting in ascending order by last name.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.