Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array by two object properties using anonymous function

I have the following array:

Array
(
    [0] => stdClass Object
        (
            [timestamp] => 1
            [id] => 10
        )

    [1] => stdClass Object
        (
            [timestamp] => 123
            [id] => 1
        )

    [2] => stdClass Object
        (
            [timestamp] => 123
            [id] => 2
        )

) 

I'm currently using the following code to sort the array by the timestamp property:

function sort_comments_by_timestamp(&$comments, $prop)
{
    usort($comments, function($a, $b) use ($prop) {
        return $a->$prop < $b->$prop ? 1 : -1;
    });
}

How can I also sort id by id descending when timestamp is the same?

like image 300
PeeHaa Avatar asked Dec 22 '11 00:12

PeeHaa


People also ask

How do you sort objects by property?

In JavaScript, we use the sort() function to sort an array of objects. The sort() function is used to sort the elements of an array alphabetically and not numerically. To get the items in reverse order, we may use the reverse() method.

How do you sort an array of objects by property value in PHP?

The usort() function is an inbuilt function in PHP which 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.


2 Answers

Suggestion is to send in an array with $props

function sort_comments_by_timestamp(&$comments, $props)
{
    usort($comments, function($a, $b) use ($props) {
        if($a->$props[0] == $b->$props[0])
            return $a->$props[1] < $b->$props[1] ? 1 : -1;
        return $a->$props[0] < $b->$props[0] ? 1 : -1;
    });
}

And then call it with

sort_comments_by_timestamp($unsorted_array,array("timestamp","id"));

If you want it to work with X number of $props you can make a loop inside the usort always comparing a property with its preceding property in the array like this:

function sort_comments_by_timestamp(&$comments, $props)
{
    usort($comments, function($a, $b) use ($props) {
        for($i = 1; $i < count($props); $i++) {
            if($a->$props[$i-1] == $b->$props[$i-1])
                return $a->$props[$i] < $b->$props[$i] ? 1 : -1;
        }
        return $a->$props[0] < $b->$props[0] ? 1 : -1;
    });
}

Cheers!

like image 115
Andreas Helgegren Avatar answered Oct 12 '22 04:10

Andreas Helgegren


function sort_comments_by_timestamp(&$comments, $prop)
{
    usort($comments, function($a, $b) use ($prop) {
        if ($a->$prop == $b->$prop)
          return $b->id - $a->id;
        else
          return $a->$prop < $b->$prop ? 1 : -1;
    });
}

The above sorts first by the $prop parameter and then secondary by id.

like image 37
Matthew Avatar answered Oct 12 '22 04:10

Matthew