[英]Sort array in array in array in PHP
I have array like this: 我有这样的数组:
$items = array(
[1] => array(
['Name'] =>"Item 1",
['Prices'] => array(
['Base price'] => 80.25,
['Discount'] => 5.50
)
),
[2] => array(
['Name'] =>"Item 2",
['Prices'] => array(
['Base price'] => 70.25,
['Discount'] => 4.50
)
)
);
How can I sort $items that by "Base price"? 如何按“基本价格”对$ items进行排序? I want to have lowest price in first element, highest in last element of output array with same structure.
我希望具有相同结构的输出数组的第一个元素的价格最低,最后一个元素的价格最高。
Expected output: 预期产量:
$items = array(
[1] => array(
['Name'] =>"Item 2",
['Prices'] => array(
['Base price'] => 70.25,
['Discount'] => 4.50
)
),
[2] => array(
['Name'] =>"Item 1",
['Prices'] => array(
['Base price'] => 80.25,
['Discount'] => 5.50
)
)
);
I don't understand array_multisort() and how to use it in my case. 我不了解array_multisort()以及如何在我的情况下使用它。
This is how you could use array_multisort
: 这就是使用
array_multisort
:
foreach ($items as $item) {
$sort[] = $item['Prices']['Base price'];
}
array_multisort($sort, SORT_ASC, $items);
Like Jan was saying, you can also use usort
: 就像Jan所说的那样,您还可以使用
usort
:
usort($items, function($a, $b) {
return $a['Prices']['Base price'] - $b['Prices']['Base price'];
});
I hope this helps. 我希望这有帮助。 I'm using
usort()
with a callback function: 我将
usort()
与回调函数一起使用:
$arr = array(
array(
'foo' => 'bar',
'data' => array(
'basePrize' => 5
)
),
array(
'foo' => 'bar2',
'data' => array(
'basePrize' => 2
)
)
);
usort($arr, function($a, $b) {
if($a['data']['basePrize'] === $b['data']['basePrize']) {
return 0;
}
if($a['data']['basePrize'] > $b['data']['basePrize']) {
return 1;
}
return -1
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.