我有这样的数组:
$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
)
)
);
如何按“基准价格”对$项目进行排序? 我想在第一个元素中具有最低价格,在具有相同结构的输出数组的最后一个元素中最高。
预期产出:
$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
)
)
);
我不了解array_multisort()以及如何在我的情况下使用它。
答案 0 :(得分:2)
您可以使用array_multisort
:
foreach ($items as $item) {
$sort[] = $item['Prices']['Base price'];
}
array_multisort($sort, SORT_ASC, $items);
就像Jan说的那样,你也可以使用usort
:
usort($items, function($a, $b) {
return $a['Prices']['Base price'] - $b['Prices']['Base price'];
});
答案 1 :(得分:1)
我希望这会有所帮助。我正在使用带有回调函数的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
});