PHP: Sorting custom classes, using java-like Comparable?

后端 未结 4 1743
逝去的感伤
逝去的感伤 2021-02-06 12:37

How can I make my own custom class be sortable using sort() for example?

I\'ve been scanning the web to find any method of making a class Comparable like in Java but wi

4条回答
  •  花落未央
    2021-02-06 13:02

    The simplest way to do this is to simply use usort on a method within the class that accepts as input an array of matching objects. This is example 3 in the documentation linked to above. However, this is somewhat clunky and ugly.

    A better way is to create a new type of array class specific to the desired objects using ArrayAccess. This will enable you to use the custom array like you'd expect but then also be able to run arbitrary sorting methods on the array.

    Under the hood, you'd likely still want to use usort, but you'd be hiding that fact behind a much nicer interface that might look like this:

    $array = new GenreCollection();
    
    $array[] = new Genre(1); // Genre's constructor is a factory that can load genres via an ID
    $array[] = new Genre(2);
    $array[] = new Genre(3);
    $array[] = new Genre(4);
    $array[] = new Genre(5);
    
    // Example Sorts
    $array->SortByName();
    $array->SortByDateInvented();
    $array->SortByID();
    $array->SortBySubGenres(); // Arranges Genres into a hierarchy where 'Death Metal' comes with other metal after 'Heavy Metal' - Add in a nest-level value for making dropdowns and other nested lists.
    

提交回复
热议问题