How to sort multi dimensional array of objects in php?

by hal.littel , in category: PHP General , a year ago

How to sort multi dimensional array of objects in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , a year ago

@hal.littel 

To sort a multi-dimensional array of objects in PHP, you can use the usort() function with a custom comparison function. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Sample multi-dimensional array of objects
$objects = [
    ['name' => 'John', 'age' => 25],
    ['name' => 'Alice', 'age' => 30],
    ['name' => 'Bob', 'age' => 20],
];

// Custom comparison function
function compareObjects($a, $b) {
    if ($a['age'] == $b['age']) {
        return 0;
    }
    return ($a['age'] < $b['age']) ? -1 : 1;
}

// Sort the multi-dimensional array of objects by age
usort($objects, 'compareObjects');

// Print the sorted array
print_r($objects);


In this example, the usort() function is used to sort the $objects array based on the 'age' key of each element. The compareObjects() function compares the 'age' values of two objects and returns -1, 0, or 1 to indicate their order. Finally, the sorted array is printed using print_r().

Related Threads:

How to sort array of objects in laravel?
How to sort an array in PHP?
How to sort array by key in PHP?
How to convert xml into array of objects in php?
How to sort objects in ember.js?
How to read multi layer php object?