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"? 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.
This is how you could use 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
:
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:
$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
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.