1

How can I sort the $item type based on the order? This is what I currently have:

$order = ['AA', 'zl', 'Dr', 'co', 'og'];

$items->sort(
    function ($a, $b) use ($order) {
        return strcmp($b->type, $a->type) // how do I apply the order here?
            ?: strcmp($b->date, $a->date);
    }
);

Basically it's a two column sort where it first sorts by type and then sorts by date. The type would be sorted using the array order rather than the typical alphabetical order.

1 Answer 1

2

You could compare the keys in $order corresponding to the type of each item.

    return ($order[$b->type] - $order[$a->type]) 
           ?: strcmp($b->date, $a->date);

This should work if all of your items have types contained in $order. If not, you'll get undefined index errors which will mess up the sort. But since you haven't specified how items like that should be sorted in your question, I'm assuming that they all do.

Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.