Native PHP Sort array of objects by property

Usually, it is very often necessary to sort the data in an array. But when in the array we have objects it happened little bit difficult.
Fast solution for sorting array objects by property name.
Bacis solution (PHP 5.3+) :

function sortArrayWithObjects($array, $property)
{
    usort($array, function ($a, $b) use ($property) {
        return (($a->$property == $b->$property) ? 0 : (($a->$property < $b->$property) ? -1 : 1));
        //[short version] return strcmp($a->$property, $b->$property);
    });
    return $array;
}

$obj1 = new stdClass();
$obj2 = clone $obj1;
$obj3 = clone $obj2;
$obj1->name = 'B';
$obj2->name = 'C';
$obj3->name = 'A';
$data = [$obj1, $obj2, $obj3];
$result = sortArrayWithObjects($data, 'name');
echo '<pre>';
var_dump($result);
echo '</pre>';

Result:
Continue reading Native PHP Sort array of objects by property

How to sort array with objects by object property in Yii 2?

If you want to sort your array with objects by specific property in Yii 2 then you can use beautiful method ArrayHelper::multisort (&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR)
Example (you have unsorted array ‘history’ with objects):

Array
(
    [0] => stdClass Object
        (
            [sent_date] => 2016-01-28 13:42:10
            [type] => sent
            [body] => Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for lorem ipsum
        )

    [1] => stdClass Object
        (
            [sent_date] => 2016-01-29 10:08:35
            [type] => sent
            [body] => Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for lorem ipsum
        )

    [2] => stdClass Object
        (
            [sent_date] => 2016-01-31 10:08:35
            [type] => sent
            [body] => Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for lorem ipsum
        )

    [3] => stdClass Object
        (
            [sent_date] => 2015-12-01 10:08:35
            [type] => sent
            [body] => Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for lorem ipsum
        )

)

Continue reading How to sort array with objects by object property in Yii 2?