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!


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);