代码之家  ›  专栏  ›  技术社区  ›  Haim Evgi

php排序数组问题

  •  1
  • Haim Evgi  · 技术社区  · 15 年前

    我想按字母表对数组排序

    Avi
    Beni
    ..
    ..
    avi
    beni
    

    如果我想:

    Avi
    avi
    Beni
    beni
    ..
    ..
    

    3 回复  |  直到 15 年前
        1
  •  2
  •   Eineki    15 年前

    以及 解决方案在某些初始阵列配置中失败。

    让我们做些测试,找出解决办法。

    <?php
    $array1 = $array2 = $array3 = $array4 = $array5 = array('IMG1.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG2.png');
    
    // This result is the one we nee to avoid
    sort($array1);
    echo "Standard sorting\n";
    print_r($array1);
    
    // img2.png and IMG2.png are not in the desired order
    // note also the array index order in the result array
    natcasesort($array2);
    echo "\nNatural order sorting (case-insensitive)\n";
    print_r($array2);
    
    // img1.png and IMG1.png are not in the desired order
    usort($array3, 'strcasecmp');
    echo "\nNatural order sorting (usort-strcasecmp)\n";
    print_r($array3);
    
    // Required function using the standard sort algorithm
    function mySort($a,$b) {
      if (strtolower($a)== strtolower($b))
        return strcmp($a,$b);
      return strcasecmp($a,$b);
    }
    
    usort($array4, 'mySort');
    echo "\nStandard order sorting (usort-userdefined)\n";
    print_r($array4);
    
    // Required function using the natural sort algorithm
    function myNatSort($a,$b) {
      if (strtolower($a)== strtolower($b))
        return strnatcmp($a,$b);
      return strnatcasecmp($a,$b);
    }
    
    usort($array5, 'myNatSort');
    echo "\nNatural order sorting (usort-userdefined)\n";
    print_r($array5);
    

        2
  •  4
  •   shamittomar    15 年前

    你可以用 netcasesort() . 它使用不区分大小写的“自然顺序”算法对数组进行排序。

    这样做:

    natcasesort($array);
    
        3
  •  2
  •   Sjoerd    15 年前
    推荐文章