Erik van de Ven
Erik van de Ven

Reputation: 4975

Sort based on multiple criteria on keys and values

I would like to sort the array below using PHP. The main problem is that I need to sort the array based on multiple criteria:

So this array

array(
    [Beslist.nl] => Array
        (
            [price] => 141,63
        )

    [Wehkamp.nl] => Array
        (
            [price] => none
        )

    [Bol.com] => Array
        (
            [price] => none
        )

    [Zalando.nl] => Array
        (
            [price] => none
        )

    [Webwinkel.nl] => Array
        (
            [price] => none
        )

    [Overig.nl] => Array
        (
            [price] => none
        )
)

Should be sorted like this:

array(
    [Beslist.nl] => Array
        (
            [price] => 141,63
        )

    [Bol.com] => Array
        (
            [price] => none
        )

    [Overig.nl] => Array
        (
            [price] => none
        )

    [Webwinkel.nl] => Array
        (
            [price] => none
        )

    [Wehkamp.nl] => Array
        (
            [price] => none
        )

    [Zalando.nl] => Array
        (
            [price] => none
        )

)

I tried asort and ksort, but I need to sort based on multiple criteria, which makes it more complex. I was hoping I could sort the records using SQL (when I read the records from the database). However, the price needs to be calculated afterwards; that is why I need to use PHP.

Anyone who can help me out?

Upvotes: 0

Views: 616

Answers (1)

deceze
deceze

Reputation: 522332

There are perfectly suitable approaches detailed here, but considering the actual structure of your array, this probably requires a bit more explanation. Specifically, here's how you can sort by both keys and values:

uksort($array, function ($siteA, $siteB) use ($array) {
    $priceA = $array[$siteA]['price'];
    $priceB = $array[$siteB]['price'];

    if ($priceA == $priceB) {
        return strcmp($siteA, $siteB);
    }
    if (!$priceB) {
        return -1;
    }
    if (!$priceA) {
        return 1;
    }
    return $priceB - $priceA;
});

You might need to adjust the specific comparisons and return logic here, but this illustrates the approach.

Upvotes: 2

Related Questions