Search code examples
phparrayssortingmultidimensional-array

Sort a 2d array by two columns, both descending


I need to sort array (lower) by the value of [price] BUT if value of [stock] = 0, I need to sort them too, but they should be placed lower than those where [stock] > 0. The function has to be for any number of subarrays, the array lower is only example.

I have array

Array
(
[0] => Array
    (
        [cardname] => Tundra Wolves
        [edition] => Legends
        [stock] => 0
        [price] => 5
        [shop] => cernyrytir.cz
    )

[1] => Array
    (
        [cardname] => Tundra Wolves
        [edition] => Legends
        [stock] => 20
        [price] => 9
        [shop] => mysticshop.cz
    )

[2] => Array
    (
        [cardname] => Tundra Wolves
        [edition] => Legends
        [stock] => 5
        [price] => 5
        [shop] => najada.cz
    )
    
[3] => Array
    (
        [cardname] => Tundra Wolves
        [edition] => Legends
        [stock] => 0
        [price] => 3
        [shop] => rishada.cz
    )
)

I need array:

Array
(
[2] => Array
    (
        [cardname] => Tundra Wolves
        [edition] => Legends
        [stock] => 5
        [price] => 5
        [shop] => najada.cz
    )

[1] => Array
    (
        [cardname] => Tundra Wolves
        [edition] => Legends
        [stock] => 20
        [price] => 9
        [shop] => mysticshop.cz
    )
    
[3] => Array
    (
        [cardname] => Tundra Wolves
        [edition] => Legends
        [stock] => 0
        [price] => 3
        [shop] => rishada.cz
    )

[0] => Array
    (
        [cardname] => Tundra Wolves
        [edition] => Legends
        [stock] => 0
        [price] => 5
        [shop] => cernyrytir.cz
    )
)

Solution

  • Ok, this is what you want then:

    foreach($a as $key => $value) {
        if ($value['stock'] > 0) {
            $stock[] = $value;
            $stockPrice[] = $value['price'];
        } else {
            $zeroStock[] = $value;
            $zeroStockPrice[] = $value['price'];
        }
    }
    
    array_multisort($stockPrice, SORT_ASC, $stock);
    array_multisort($zeroStockPrice, SORT_ASC, $zeroStock);
    
    $array = array_merge($stock, $zeroStock);
    

    Now $array has what you want.