I have this array in PHP:
In PHP APIs I have this array and want to sort ot by custom_price, but not getting how to acheive so ..
Array
(
[0] => Array
(
[id] => 1204
[custom_price] => 33.1500
)
[1] => Array
(
[id] => 1199
[custom_price] => 16.83
)
[2] => Array
(
[id] => 1176
[custom_price] => 16.83
)
[3] => Array
(
[id] => 1173
[custom_price] => 11.73
)
[4] => Array
(
[id] => 1170
[custom_price] => 22.5
)
)
How i can sort from .. high to low & low to high .. by custom_price
Using usort
:
high to low
usort($input, function ($a, $b) {return $a['custom_price'] < $b['custom_price'];});
print_r( $input );
low to high
usort($input, function ($a, $b) {return $a['custom_price'] > $b['custom_price'];});
print_r( $input );
http://php.net/manual/en/function.usort.php
This solution might help you.
function sortByOrder($a, $b) {
return $a['custom_price'] - $b['custom_price'];
}
usort($myArray, 'sortByOrder');
Or
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
aasort($your_array,"custom_price");
here is reference link
use
array_multisort()
withSORT_DESC
andSORT_ASC
<?php
$MYarray=
array(
0 => array(
"id"=> 1204,
"custom_price"=> 33.1500
),
1 => array(
"id"=> 1199,
"custom_price"=> 16.83
),
2 => array(
"id"=> 1176,
"custom_price"=> 316.83
));
$custom_price = array();
foreach ($MYarray as $key => $row)
{
$custom_price[$key] = $row['custom_price'];
}
array_multisort($custom_price, SORT_DESC, $MYarray);
var_dump($MYarray);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With