Jump to content

Adding unlimited amount of names into an array and then printing them in alphabetical order


Go to solution Solved by cyberRobot,

Recommended Posts

Hello. First of all, English is not my main language so I'm sorry if I make some mistakes in my text...
 
Anyway, my problem is that I really have no clue how to do this task I was given: I need to create a form where I can write names and then save them and do this for unlimited times. After I have added names, I need to sort them alphabetically from A-Z. I have done it like this so far, just the sorting is missing.
 
This job has two files, index.php and persons.php.

index.php:

<?php
include "persons.php";
?>
<!DOCTYPE html>
<!-- -->
<html>
    <head>
        <meta charset="UTF-8">
        <title><Task</title>
    </head>
    <body>
        <form action="">
            First name: <input type="text" name="first_name">
            Last name: <input type="text" name="last_name"><br>
            <input type="submit" name="do" value="Add"><br>
            Alphabetical order by Last name:<input type="radio" name="alphabetical" value="ln_first" checked><br>
            Alphabetical order by First name:<input type="radio" name="alphabetical" value="fn_first"><br>
            <input type="submit" name="do" value="Sort">
        </form>
        <?php
        if (isset($_GET["first_name"]) && isset($_GET["last_name"]) && $_GET["first_name"] != "" && $_GET["last_name"] != "" || $_GET["do"] == "Sort")
        {
            $persons = new persons($_GET["first_name"], $_GET["last_name"]);
            $str = "";
            switch ($_GET["do"])
            {
                case "Add":
                    $persons->Add($_GET["first_name"], $_GET["last_name"]);
                    break;
                case "Sort":
                    $str = $persons->Sort();
                    break;
                default:
                    $str = "Something went wrong.";
            }
            print($str);
        }
        else
            print("Give a real name.");
        ?>
    </body>
</html>

persons.php:

<?php
session_start();
/**
*/
class persons
{
private $persons;

public function __construct()
{
if (isset ($_SESSION["persons"]))
$this->persons = $_SESSION["persons"];
else
$this->persons = array();
}

public function __destruct()
{
$_SESSION["persons"] = $this->persons;
}

/**
*
* @param type $first_name
* @param type $last_name
* @return string
*/
public function Add($first_name, $last_name)
{
$this->persons[$first_name] = $last_name;
return "Added.";
}

/**
*
* @return string
*/
public function Sort()
{
$str = "<table>\n";
foreach ($this->persons as $first_name => $last_name)
{
$str .= "<tr><td>$first_name</td><td>$last_name</td></tr>\n";
}
$str .= "</table>\n";
return $str;
}
}

So I just need to add the sorting somewhere in the code, but I just don't know where. This task was given in my school and it is the first course of php coding. I am a newbie in this thing...

Edited by Markuzi94

Use the sort() function.

Well the problem is that I don't know how to use it correctly on this code. I have tried sort(), usort(). I don't think we have studied that in school... I'm not sure though. At least our teacher does not use it in any examples even some of them includes sorting.

Well the problem is that I don't know how to use it correctly on this code. I have tried sort(), usort(). I don't think we have studied that in school... I'm not sure though. At least our teacher does not use it in any examples even some of them includes sorting.

 

I provided a link to the manual page for the function. All you need to do is 

 

sort($myArray);

 

and the elements in the array will be sorted.

  • Solution

The code is on the first post. It's working except the sorting.

 

You mentioned that you tried sort() and usort() and scootstah was wondering what that code looked like.

 

 

 

Since the first names are stored as the array keys, you would use ksort() to sort by first name. Sorting by last name would be done with sort() as others have suggested. Try doing something like the following:

public function Sort()
{
    if($_GET['alphabetical'] == 'ln_first') {  //sorting by last name
        sort($this->persons);
    } else {                                   //else...sorting by first name
        ksort($this->persons)
    }
 
 
    $str = "<table>\n";
    foreach ($this->persons as $first_name => $last_name)
    {
        $str .= "<tr><td>$first_name</td><td>$last_name</td></tr>\n";
    }
    $str .= "</table>\n";
    return $str;
}

With that said, what happens when you get two people with the same first name? If you add "John Smith", for example, the information will be overwritten when you add "John Jones". Instead of using the first (or last) name as the array key, you'll want to use a value that's going to be unique. Basically, you could let PHP create the key for you which would be a number. First and last name would then be stored as a multi-dimensional array.

$this->persons[] = array(
    'firstName' => $first_name,
    'lastName'  => $last_name
);
Edited by cyberRobot

 

You mentioned that you tried sort() and usort() and scootstah was wondering what that code looked like.

 

 

 

Since the first names are stored as the array keys, you would use ksort() to sort by first name. Sorting by last name would be done with sort() as others have suggested. Try doing something like the following:

public function Sort()
{
    if($_GET['alphabetical'] == 'ln_first') {  //sorting by last name
        sort($this->persons);
    } else {                                   //else...sorting by first name
        ksort($this->persons)
    }
 
 
    $str = "<table>\n";
    foreach ($this->persons as $first_name => $last_name)
    {
        $str .= "<tr><td>$first_name</td><td>$last_name</td></tr>\n";
    }
    $str .= "</table>\n";
    return $str;
}

I got the task to work like it should now. I just changed that "sort($this->persons);" to "natsort($this->persons);" because with "sort" it printed the names like:

 

(Added names Name A, Name B and Name C)

[0] A

[1] B

[2] C

 

with natsort, it prints them as:

Name A

Name B

Name C

 

so it now works perfectly. Thank you.

I got the task to work like it should now. I just changed that "sort($this->persons);" to "natsort($this->persons);" because with "sort" it printed the names like:

 

(Added names Name A, Name B and Name C)

[0] A

[1] B

[2] C

 

with natsort, it prints them as:

Name A

Name B

Name C

 

so it now works perfectly. Thank you.

 

Ah, I forgot that sort() doesn't maintain the array keys. To maintain the keys, you could also use asort().

http://php.net/manual/en/function.asort.php

 

And it looks like natsort(), as you have found, also maintains the keys.

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.