Sort array of objects by property value


usort($myArray, function ($a, $b) {
    return strcmp($a->myPropery, $b->myPropery);
});
PHP

Sort by predefined order:

$predefinedOrder = [1, 5, 2, 6];

usort($arrayOfObjects, function ($a, $b) use ($predefinedOrder) {

    $flipped = array_flip($predefinedOrder);
    $left = $flipped[$a->myPropery];
    $right = $flipped[$b->myPropery];
    return $left >= $right;
});
PHP

Leave a Reply

Your email address will not be published. Required fields are marked *