Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Sort Array of Objects by Object Fields in PHP
In PHP, you can sort an array of objects by their properties using several built-in functions. Each approach offers different advantages depending on your specific requirements and coding style preferences.
Using usort() Function with a Custom Comparison Function
The usort() function provides the most flexible approach for sorting objects by custom logic ?
<?php
class Person {
public $name;
public $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
}
// Create array of objects
$people = [
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
];
// Custom comparison function
function compareByAge($a, $b) {
return $a->age <=> $b->age;
}
// Sort the array using the custom comparison function
usort($people, 'compareByAge');
// Display sorted results
foreach ($people as $person) {
echo $person->name . " - " . $person->age . "<br>";
}
?>
Bob - 25 Alice - 30 Charlie - 35
Using Anonymous Functions
You can also use anonymous functions for more concise code ?
<?php
class Product {
public $name;
public $price;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
}
$products = [
new Product("Laptop", 999.99),
new Product("Mouse", 25.50),
new Product("Keyboard", 75.00)
];
// Sort by price using anonymous function
usort($products, function($a, $b) {
return $a->price <=> $b->price;
});
foreach ($products as $product) {
echo $product->name . " - $" . $product->price . "<br>";
}
?>
Mouse - $25.5 Keyboard - $75 Laptop - $999.99
Utilizing the array_multisort() Function
For simple field-based sorting, array_multisort() combined with array_column() provides an efficient solution ?
<?php
// Convert objects to associative arrays for array_column
$students = [
(object)["name" => "John", "grade" => 85],
(object)["name" => "Sarah", "grade" => 92],
(object)["name" => "Mike", "grade" => 78]
];
// Extract grades for sorting
$grades = array_column($students, 'grade');
// Sort by grades in descending order
array_multisort($grades, SORT_DESC, $students);
foreach ($students as $student) {
echo $student->name . " - " . $student->grade . "<br>";
}
?>
Sarah - 92 John - 85 Mike - 78
Comparison
| Method | Flexibility | Performance | Best For |
|---|---|---|---|
usort() |
High | Good | Complex sorting logic |
array_multisort() |
Medium | Better | Simple field sorting |
Conclusion
Use usort() for complex sorting requirements and custom logic. For simple field-based sorting, array_multisort() with array_column() offers better performance and cleaner code.
Advertisements
