[英]Sort an object that contains an array by a specific key, DESC
I'm using the https://github.com/brunogaspar/cartify library to manage my Cart. 我正在使用https://github.com/brunogaspar/cartify库来管理我的购物车。 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
一切都很好,除了我需要能够通过price
键DESC
对array
包含的项目进行排序的事实
If I'm using the Cartify::cart()->contents()
, here's an example of one of the items contained: 如果我使用的是Cartify::cart()->contents()
,那么以下是其中一个项目的示例:
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. 如您所见,这里有一个price
键……如果我不能在班级进行排序,我将不得不在事后对这些项目进行排序。
You can do this using usort
and a custom compare function. 您可以使用usort
和自定义比较功能执行此操作。 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. 并不是将密钥硬编码到sort函数中的最优雅的解决方案,但是它可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.