TheAuzzieJesus TheAuzzieJesus - 5 months ago 13
PHP Question

How can I sort an array of stdClass Objects by a common element within the stdClass Objects?

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
)

)

Answer

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