VOOZH about

URL: https://www.geeksforgeeks.org/php/sort-array-of-objects-by-object-fields-in-php/

⇱ Sort array of objects by object fields in PHP - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort array of objects by object fields in PHP

Last Updated : 1 Jul, 2024

Sorting an array of objects by object fields means organizing the array's objects based on the values of specified properties (fields) within each object, typically in ascending or descending order, to arrange the data meaningfully.

Here we have some common approaches:

Using usort()

function is an inbuilt function in PHP that is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field. Call usort() function with first argument as the array of objects and the second argument as the comparator function based on which a comparison between two array objects has to be made.

Example:


Output
Original object array:
Array
(
 [0] => geekSchool Object
 (
 [score] => 100
 [name] => Sam
 [subject] => Data Structures
 )

 [1] => geekSchool Object
 (
 [score] => 50
 [name] => Tanya
 [subject] => Advanced Algorithms
 )

 [2] => geekSchool Object
 (
 [score] => 75
 [name] => Jack
 [subject] => Distributed Computing
 )

)

Sorted object array:
Array
(
 [0] => geekSchool Object
 (
 [score] => 50
 [name] => Tanya
 [subject] => Advanced Algorithms
 )

 [1] => geekSchool Object
 (
 [score] => 75
 [name] => Jack
 [subject] => Distributed Computing
 )

 [2] => geekSchool Object
 (
 [score] => 100
 [name] => Sam
 [subject] => Data Structures
 )

)

Using array_multisort()

The array_multisort() function in PHP sorts multiple arrays or an array of objects by specific fields. It works by extracting the fields into separate arrays, sorting them, and then reordering the original array based on the sorted keys.

Example:


Output
banana 2
apple 5
cherry 8

Using array_map() and array_column()

To sort an array of objects by object fields in PHP without `usort()` or `array_multisort()`, use `array_map()` to extract and sort specific object properties like `name`, then reorder the original array based on the sorted property values. This method achieves sorting without direct sorting functions.

Example:


Output
Array
(
 [0] => stdClass Object
 (
 [name] => Doe
 [age] => 35
 )

 [1] => stdClass Object
 (
 [name] => Jane
 [age] => 25
 ...


Comment