按值/键对数组排序 - 混合字符串和数值PHP

时间:2017-04-12 11:51:07

标签: php sorting

我需要对数组进行排序。值和键都是相同的并且是字符串。基本上,数组看起来类似于:

 $test = array(
      '1' => '1',
      '2' => '2',
      '1.5' => '1.5',
      '3' => '3',
      '4' => '4',
      '3.5' => '3.5',
      '2XS' => '2XS',
      '2XL' => '2XL',
      'XXL' => 'XXL',
    );

预期输出:

 Array
 (
     [0] => 1
     [1] => 1.5
     [2] => 2
     [5] => 3
     [6] => 3.5
     [7] => 4
     [3] => 2XL
     [4] => 2XS
     [8] => XXL
 )

有什么想法吗?

3 个答案:

答案 0 :(得分:4)

PHP code demo

<?php 
$test = array(
      '1' => '1',
      '2' => '2',
      '1.5' => '1.5',
      '3' => '3',
      '4' => '4',
      '3.5' => '3.5',
      '2XS' => '2XS',
      '2XL' => '2XL',
      'XXL' => 'XXL',
    );
$numericArray=array();
$stringsArray=array();
array_map(function($value) use (&$numericArray,&$stringsArray) {
        if(is_numeric($value))
        {
            $numericArray[]=$value;//Here we are putting numeric values
        }
        else
        {
            $stringsArray[]=$value;//Here we are putting string values
        }

}, $test);
sort($numericArray,SORT_NUMERIC);//sorting on numeric basis
sort($stringsArray,SORT_REGULAR);//sorting on string basis
$result=array_merge($numericArray,$stringsArray);//merging both of them
print_r($result);

<强>输出:

Array
(
    [0] => 1
    [1] => 1.5
    [2] => 2
    [3] => 3
    [4] => 3.5
    [5] => 4
    [6] => 2XL
    [7] => 2XS
    [8] => XXL
)

答案 1 :(得分:1)

<?php
$test = array(
    '1' => '1',
    '2' => '2',
    '1.5' => '1.5',
    '3' => '3',
    '4' => '4',
    '3.5' => '3.5',
    '2XS' => '2XS',
    '2XL' => '2XL',
    'XXL' => 'XXL',
);

function sortNandS($array){
    $nums = [];
    $strings = [];

    foreach($array as $elm) {
        is_numeric($elm) ? $nums[]= $elm : $strings[]=$elm;
    }
    sort($nums,SORT_NUMERIC);
    sort($strings,SORT_REGULAR);
    $result=array_merge($nums,$strings);

    return $result;
}

print_r(sortNandS($test));

答案 2 :(得分:1)

使用usortis_numericstrcmp函数的解决方案:

usort($test, function ($a, $b) {
    if (is_numeric($a) && is_numeric($b)) {
        return $a - $b;
    } else if (is_numeric($a) && !is_numeric($b)) {
        return -1;
    } else if (!is_numeric($a) && is_numeric($b)) {
        return 1;
    } else {
        return strcmp($a, $b);
    }
});

print_r($test);

输出:

Array
(
    [0] => 1
    [1] => 1.5
    [2] => 2
    [3] => 3
    [4] => 3.5
    [5] => 4
    [6] => 2XL
    [7] => 2XS
    [8] => XXL
)