douti19680318 2017-04-12 11:51 采纳率: 0%
浏览 84
已采纳

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

I need to sort an array. Both values and keys are the same and are strings. Basically, array looks similar to this:

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

Expected Output:

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

Any ideas?

  • 写回答

3条回答 默认 最新

  • dsfo22654 2017-04-12 11:58
    关注

    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);
    

    Output:

    Array
    (
        [0] => 1
        [1] => 1.5
        [2] => 2
        [3] => 3
        [4] => 3.5
        [5] => 4
        [6] => 2XL
        [7] => 2XS
        [8] => XXL
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里