settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Order by Age - PHP Classes and Objects Task

+4 votes

You will receive an unknown number of lines. On each line, you will receive array with 3 elements.

  • The first element will be а string and represents the name of the person.
  • The second element will be a string and will represent the ID of the person.
  • The last element will be an integer and represents the age of the person.

When you receive the command "End", stop receiving input and print all the people, ordered by age.

Examples:

order by age php classes objects task

asked in PHP category by user hues

1 Answer

+3 votes

Here is the answer - I've used usort() php function to sort the age elements of the array:

<?php

class Person
{
    private $name;
    private $id;
    private $age;

    /**
     * Person constructor.
     * @param $name
     * @param $id
     * @param $age
     */
    public function __construct($name, $id, $age) {
        $this->name = $name;
        $this->id = $id;
        $this->age = $age;
    }

    /**
     * @return mixed
     */
    public function getName() {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name): void {
        $this->name = $name;
    }

    /**
     * @return mixed
     */
    public function getId() {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id): void {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getAge() {
        return $this->age;
    }

    /**
     * @param mixed $age
     */
    public function setAge($age): void {
        $this->age = $age;
    }
}

$input = readline();
$people = [];//2nd array used to write the objects from the class Person

while ($input !== "End") {

    $arr = explode(" ", $input);//1st array used to write the input

    $name = $arr[0];
    $id = $arr[1];
    $age = intval($arr[2]);

    $person = new Person($name, $id, $age);//use __construct

    $people[] = $person;

    $input = readline();
}

usort($people, function (Person $p1, Person $p2) {
    $age1 = $p1->getAge();
    $age2 = $p2->getAge();
    return $age1 <=> $age2;
});//sorting the array

foreach ($people as $person) {
    echo $person->getName() . " with ID: " .
        $person->getId() . " is " .
        $person->getAge() . " years old." . PHP_EOL;
}
answered by user andrew
...