I've had trouble with the examples in the PHP manual, so I'd like to ask this here...
I have an array of objects.. Is there a way to sort it based on the contents of the object?
For example, my array is:
Array
(
[0] => stdClass Object
(
[id] => 123
[alias] => mike
)
[1] => stdClass Object
(
[id] => 456
[alias] => alice
)
[2] => stdClass Object
(
[id] => 789
[alias] => zeke
)
[3] => stdClass Object
(
[id] => 987
[alias] => dave
)
)
How do I sort the array by the [alias] of the objects?
In the example, the output should be:
Array
(
[0] => stdClass Object
(
[id] => 456
[alias] => alice
)
[1] => stdClass Object
(
[id] => 987
[alias] => dave
)
[2] => stdClass Object
(
[id] => 123
[alias] => mike
)
[3] => stdClass Object
(
[id] => 789
[alias] => zeke
)
)
Thanks in advance!
Sorting array of objectsArrays of objects can be sorted by comparing the value of one of their properties.
To sort an array of objects, use the sort() method with a compare function. A compareFunction applies rules to sort arrays by defined our own logic. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.
Example 1: Sort Array by Property NameThe sort() method sorts its elements according to the values returned by a custom sort function ( compareName in this case). Here, The property names are changed to uppercase using the toUpperCase() method. If comparing two names results in 1, then their order is changed.
The java. util. Arrays. sort(Object[]) method sorts the specified array of Objects into ascending order according to the natural ordering of its elements.
Use usort()
. You specify a function to do that comparison and the sort is done based on the function. E.g.:
function my_comparison($a, $b) {
return strcmp($a->alias, $b->alias);
}
$arr = ...;
usort($arr, 'my_comparison');
I think the order is missing, I've found this other function
<?php
/**
* Sort array of objects by field.
*
* @autor Lea Hayes
* @param array $objects Array of objects to sort.
* @param string $on Name of field.
* @param string $order (ASC|DESC)
*/
function sort_on_field(&$objects, $on, $order = 'ASC') {
$comparer = ($order === 'DESC')
? "return -strcmp(\$a->{$on},\$b->{$on});"
: "return strcmp(\$a->{$on},\$b->{$on});";
usort($objects, create_function('$a,$b', $comparer));
}
$order = ($_GET['order'] === 'asc') ? 'ASC' : 'DESC';
sort_on_field($arr, 'alias', $order);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With