排序对象的线性数组在php


Sorting linear arrays of objects in php

我在php中有一个对象数组,如:

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


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

现在,我想按照学生的出生日期对上面的数组进行排序。我尝试了以下方法:
1-创建一个新的关联数组,以$dateOfBirth为键,如:

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

2-使用ksort php函数
3-将这个关联数组重新转换为线性索引数组。

虽然这个策略有效,但也有潜在的缺陷。两个学生可能有相同的出生日期,在这种情况下,只有一个会在数组中保存。此外,转换和再转换数组,to和from是关联的,稍微需要大量的计算。

谁能提出一个更好的替代方案?

PS:我避免使用任何排序算法,如快速或合并排序。

答案就在array_multisort()中

参考以下文章:如何排序的关联数组数组的值给定的关键在PHP?

你可以使用它,但如果没有任何排序算法,我不知道。

<?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);
?>