Example Input:
$weights = ['1 Kg','300 g','1.5 Kg','20 g','5 Kg'];
Output should be
$sorted_weights = ['20 g','300 g','1 Kg','1.5 Kg','5 Kg'];
Example Input:
$weights = ['1 Kg','300 g','1.5 Kg','20 g','5 Kg'];
Output should be
$sorted_weights = ['20 g','300 g','1 Kg','1.5 Kg','5 Kg'];
Please use the below code and let me know if it helps or not:
$weights = ['1 Kg','300 g','1.5 Kg','20 g','5 Kg'];
$r = [];
foreach ($weights as $v) {
if (strpos($v, 'g') !== false) {$k = 1;} // 1 g
if (strpos($v, 'Kg') !== false) {$k = 1000;} // 1 kilogram = 1000 g
$r[floatval($v)*$k] = $v;
}
ksort($r);//ksort used to sort array by key
print_r($r);
usort is the appropriate function to sort arrays with values that need to be evaluated or converted against each other. The following example assumes that only values with g or kg are available.
$weights = ['1 Kg','300 g','1.5 Kg','20 g','5 Kg', '1000 g'];
usort($weights, function($a,$b){
$a = stripos($a,'k') ? 1000 * floatval($a) : floatval($a);
$b = stripos($b,'k') ? 1000 * floatval($b) : floatval($b);
return $a <=> $b;
});
/*
array (
0 => "20 g",
1 => "300 g",
2 => "1 Kg",
3 => "1000 g",
4 => "1.5 Kg",
5 => "5 Kg",
)
*/