0

I'm using the https://github.com/brunogaspar/cartify library to manage my Cart. Things are good, except the fact that I need to be able to sort the items contained within the array by the price key DESC

If I'm using the Cartify::cart()->contents(), here's an example of one of the items contained:

array(
    'id'      => 'sku_123ABC',
    'qty'     => 1,
    'price'   => 39.95,
    'name'    => 'T-Shirt',
    'options' => array(
        'size'  => 'L',
        'color' => 'Red'
    )

As you can see, there's a price key ... and if I can't sort on the class level, I'll have to sort these items after the fact.

dcolumbus
  • 9,596
  • 26
  • 100
  • 165
  • possible duplicate of [How to sort an array of associative arrays by value of a given key in PHP](http://stackoverflow.com/questions/1597736/how-to-sort-an-array-of-associative-arrays-by-value-of-a-given-key-in-php) – Dominik Sep 21 '13 at 22:38

1 Answers1

1

You can do this using usort and a custom compare function. Something like this:

usort($myArray, function ($a, $b) {
    if ($a['price'] == $b['price']) {
        return 0;
    }
    return ($a['price'] < $b['price']) ? 1 : -1;
});

Not the most elegant solution to hard-code the key into the sort function, but it will work.

Pj Dietz
  • 921
  • 9
  • 16