What I'm trying to do is sort a multi-dimensional array that contains decimal values. From what I've tested, floats are having trouble being ordered properly.
Array
(
[0] => Array
(
[company] => Ebay
[weight] => 4.6
)
[1] => Array
(
[company] => Ebay
[weight] => 1.7
)
[2] => Array
(
[company] => Ebay
[weight] => 3.7
)
)
usort($array, 'order_by_weight');
// Sorts DESC highest first
function order_by_weight($a, $b) {
return $b['weight'] - $a['weight'];
}
What is the best way to sort these numbers in descending?
You can sort by any key (also nested like 'key1. key2. key3' or ['k1', 'k2', 'k3'] ) It works both on associative and not associative arrays ( $assoc flag)
Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements.
The arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value. Tip: Use the krsort() function to sort an associative array in descending order, according to the key.
$arr = array(
array('company' => 'A', 'weight' => 4.6),
array('company' => 'B', 'weight' => 1.7),
array('company' => 'C', 'weight' => 3.7),
);
usort($arr, 'order_by_weight');
function order_by_weight($a, $b) {
return $b['weight'] > $a['weight'] ? 1 : -1;
}
var_dump($arr);
PS: it's not a rocket science - this exact "trick" is used as the first example at http://php.net/usort
You can do this with anonymous function in just one line
$arr = array(
array('company' => 'A', 'weight' => 4.6),
array('company' => 'B', 'weight' => 1.7),
array('company' => 'C', 'weight' => 3.7),
);
usort($arr, function($a, $b) { return $b['weight'] > $a['weight'] ;});
print_r($arr);
Hope this helps :)
You can sort the array using array_multisort, altough, this is often used to sort on multiple array values instead of one.
echo "<pre>";
$a = array(
array('company' => 'ebay', 'weight' => 4.6),
array('company' => 'ebay', 'weight' => 1.7),
array('company' => 'ebay', 'weight' => 3.7),
array('company' => 'ebay', 'weight' => 2.7),
array('company' => 'ebay', 'weight' => 9.7),
array('company' => 'ebay', 'weight' => 0.7),
);
$company = array();
$weight = array();
foreach($a as $key=>$val) {
array_push($company, $val['company']);
array_push($weight, $val['weight']);
}
array_multisort($weight, SORT_ASC, $a);
print_r($a);
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