###### dounielong7728
2017-10-09 12:39 阅读 200

# 当值具有字符串和数字时，如何对数组进行排序

I have an array i want to sort it into ascending order.

Below is array i have.

``````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
``````

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享

#### 3条回答默认 最新

• 已采纳
drk7700 2017-10-09 13:33

You just need to write custom string parts comparison function for `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);
``````
点赞 评论 复制链接分享
• dpw30157 2017-10-09 13:08

Simply convert these strings to float values. Can be done easily with 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);
``````
点赞 评论 复制链接分享
• dongnong3019 2017-10-09 13:44

You can sort as numeric with the flag `SORT_NUMERIC`

``````asort(\$array, SORT_NUMERIC);
``````

Using this array:

``````\$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` produced this list:

• 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.2mm x 76.2mm
• 80mm x 80mm
• 100mm x 100mm
• 101.6mm x 101.6mm

which looks good to me :)

点赞 评论 复制链接分享