-1

I have an array of objects in php, like:

array([0] => $obj1,
      [1] => $obj2,
      ...)

where, $objN is an object of:

Class Student {
    public $name;
    public $fatherName;
    public $dateOfBirth;
}

Now, I want to sort the above array as per the date of birth of students. I tried the following approach:
1- Creative a new associative array with $dateOfBirth as key, like:

array($dateOfBirth1 => $obj1,
      $dateOfBirth2 => $obj2,
      ...)

2- Use ksort php function.
3- Re-convert this associative array into linear indexed array.

While this strategy works, there are potential flaws. Two students may have same date of births, in which case, only one will persist here, in array. Also, it's slightly computationally intensive to convert and reconvert arrays, to and from being associative.

Can someone suggest a better alternative?

PS: I am avoiding using any sorting algos like quick or merge sort.

Yo Yo Money Singh
  • 679
  • 3
  • 11
  • 22

2 Answers2

0

The answer lies in array_multisort().

Refer the following post: How to sort an array of associative arrays by value of a given key in PHP?

Community
  • 1
  • 1
Yo Yo Money Singh
  • 679
  • 3
  • 11
  • 22
0

You could use that, but without any sorting algos i dunno.

<?php
  Class Student{
    public $name;
    public $fatherName;
    public $dateOfBirth;
    function __construct($name, $fatherName, $dateOfBirth) {
      $this->name = $name;
      $this->fatherName = $fatherName;
      $this->dateOfBirth = $dateOfBirth;
    }
  }

  date_default_timezone_set('America/Los_Angeles');

  $students = array(
    new Student("John", "Father_John", "2014-03-24"),
    new Student("Bob", "Father_Bob", "2014-02-24"),
    new Student("Patrick", "Father_Patrick", "2014-02-24"),
    new Student("John", "Father_John", "2014-05-24"),
  );

  function sortBydateOfBirth($student_1, $student_2) {
    $diff = strtotime($student_2->dateOfBirth) - strtotime($student_1->dateOfBirth);
    if ($diff == 0) {
      return 0;
    } else if ($diff < 0) {
      return 1;
    } else {
      return -1;
    }
  }

  usort($students, "sortBydateOfBirth");
  print_r($students);
?>
Navid EMAD
  • 382
  • 1
  • 15