-1

How can I sort the following array by [sequence_number] in descending order in PHP?

Array
(
    [0] => stdClass Object
        (
            [debate_id] => 1
            [stakeholder_id] => 1
            [sequence_number] => 1
            [title] => SLIDE 1 - STAKEHOLDER 1
            [content] => This is the first slide for STAKEHOLDER 1
        )

    [1] => stdClass Object
        (
            [debate_id] => 1
            [stakeholder_id] => 1
            [sequence_number] => 4
            [title] => SLIDE 2 - STAKEHOLDER 1
            [content] => This is the second slide for STAKEHOLDER 1
        )

    [2] => stdClass Object
        (
            [debate_id] => 1
            [stakeholder_id] => 1
            [sequence_number] => 3
            [title] => SLIDE 3 - STAKEHOLDER 1
            [content] => This is the third slide for STAKEHOLDER 1
        )

)
TheAuzzieJesus
  • 587
  • 9
  • 23

2 Answers2

2

Try this:

usort($array, function($obj1, $obj2) {
    return $obj2->sequence_number - $obj1->sequence_number;
});
Ismail RBOUH
  • 10,292
  • 2
  • 24
  • 36
2

You can use usort, Here is how you can do it for your example:

function compare_func($a, $b)
{
    if ($a->sequence_number == $b->sequence_number) {
        return 0;
    }
    return ($a->sequence_number < $b->sequence_number) ? -1 : 1;
    // You can apply your own sorting logic here.
}

usort($arrayOfObjects, "compare_func");

usort() function sorts an array by its values using a user-supplied comparison function.

In our case compare_func is our user-supplied function.


If you want to sort the array by strings value you can use strcmp() function inside user-supplied function. Like this,

return strcmp($a["title"], $b["title"]);

Reference: http://php.net/manual/en/function.usort.php

Alok Patel
  • 7,842
  • 5
  • 31
  • 47