我有一个数组,我想按升序排序。
下面是我有的数组。
Array
[0] => 101.6mm x 101.6mm
[1] => 50.8mm x 50.8mm
[3] => 76.2mm x 76.2mm
[4] => 100mm x 100mm
[5] => 15mm x 15mm
[6] => 20mm x 20mm
[8] => 25mm x 25mm
[10] => 30mm x 30mm
[12] => 40mm x 40mm
[13] => 50mm x 50mm
[14] => 60mm x 60m
[15] => 80mm x 80mm
提前致谢
答案 0 :(得分:0)
只需将这些字符串转换为浮点值即可。可以使用PHP轻松完成。
$arr = array(
"101.6mm x 101.6mm",
"50.8mm x 50.8mm",
"76.2mm x 76.2mm",
"100mm x 100mm",
"15mm x 15mm",
"20mm x 20mm",
"25mm x 25mm",
"30mm x 30mm",
"40mm x 40mm",
"50mm x 50mm",
"60mm x 60mm",
"80mm x 80mm",
);
$endArray = array();
foreach($arr as $item){
$parts = explode("x", $item);
array_push($endArray, array(
(float)filter_var( $parts[0], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ),
(float)filter_var( $parts[1], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION )
));
}
echo '<pre>';
sort($endArray);
print_r($endArray);
答案 1 :(得分:0)
您只需要为usort()
编写自定义字符串部分比较功能:
$products = [
"101.6mm x 101.6mm",
"50.8mm x 50.8mm",
"76.2mm x 76.2mm",
"100mm x 100mm",
"15mm x 15mm",
"20mm x 20mm",
"50mm x 50.2mm",
"25mm x 25mm",
"30mm x 45mm",
"30mm x 30mm",
"40mm x 40mm",
"50mm x 50mm",
"60mm x 60m",
"80mm x 80mm",
];
usort($products,
function($a, $b) {
list($vals_a, $vals_b) = [explode('x', $a), explode('x', $b)];
$vals_a[0] = preg_replace('/(\s|mm)/mui', '',$vals_a[0]);
$vals_a[1] = preg_replace('/(\s|mm)/mui', '',$vals_a[1]);
$vals_b[0] = preg_replace('/(\s|mm)/mui', '',$vals_b[0]);
$vals_b[1] = preg_replace('/(\s|mm)/mui', '',$vals_b[1]);
if ($vals_a[0] < $vals_b[0])
return -1;
elseif ($vals_a[0] > $vals_b[0])
return +1;
else {
if ($vals_a[1] < $vals_b[1])
return -1;
elseif ($vals_a[1] > $vals_b[1])
return +1;
else return 0;
}
});
var_dump($products);
答案 2 :(得分:0)
您可以使用标记SORT_NUMERIC
asort($array, SORT_NUMERIC);
使用这个数组:
$array = ['101.6mm x 101.6mm',
'50.8mm x 50.8mm',
'76.2mm x 76.2mm',
'100mm x 100mm',
'15mm x 15mm',
'20mm x 20mm',
'25mm x 25mm',
'30mm x 30mm',
'40mm x 40mm',
'50mm x 50mm',
'60mm x 60m',
'80mm x 80mm'];
asort($array, SORT_NUMERIC);
SORT_NUMERIC
产生了这个清单:
- 15mm x 15mm
- 20mm x 20mm
- 25mm x 25mm
- 30mm x 30mm
- 40mm x 40mm
- 50mm x 50mm
- 50.8mm x 50.8mm
- 60mm x 60m
- 76.2毫米x 76.2毫米
- 80mm x 80mm
- 100mm x 100mm
- 101.6mm x 101.6mm
对我来说很好看:))