dqkxo44488 2018-04-27 06:39
浏览 295
已采纳

php - 首先使用大写字母按字母顺序对数组进行排序的函数

I'm trying to sort an array alphabetically with uppercase letters first in the array

Example:

array(7) {
  ["H"]=>
  int(1)
  ["W"]=>
  int(1)
  ["e"]=>
  int(1)
  ["l"]=>
  int(3)
  ["o"]=>
  int(2)
  ["r"]=>
  int(1)
  ["d"]=>
  int(1)
}

My code doesn't sort with uppercase letters, only alphabetically

Here is my code:

function count_char($str) {
    $chars = str_split($str);
    $char_counter = Array();
    foreach($chars as $char) 
        if ((ord($char) >= 65 && ord($char) <= 90) || 
            (ord($char) >= 97 && ord($char) <= 122)) {
            if(!isset($char_counter[$char])) $char_counter[$char] = 1;
            else $char_counter[$char] += 1;
        }
    return $char_counter;
}

var_dump(count_char("Hello World"));

My desired output is $str, I would like alphabetizing the uppers, then alphabetizing the lowers

  • 写回答

2条回答 默认 最新

  • dongyan8896 2018-04-27 06:53
    关注

    ksort() will do. You should only call ord() once and just store the result to minimize function calls. ...or better just call ctype_alpha() to ensure you are only storing letters. I recommend adding curly brackets for improved readability.

    Code: (Demo)

    function count_char($str) {
        $chars = str_split($str);
        $char_counter = array();
        foreach($chars as $char) {
            if (ctype_alpha($char)) {
                if (!isset($char_counter[$char])) {
                    $char_counter[$char] = 1;
                } else {
                    ++$char_counter[$char];
                }
            }
        }
        ksort($char_counter);
        return $char_counter;
    }
    
    var_dump(count_char("Hello World"));
    

    Output:

    array(7) {
      ["H"]=>
      int(1)
      ["W"]=>
      int(1)
      ["d"]=>
      int(1)
      ["e"]=>
      int(1)
      ["l"]=>
      int(3)
      ["o"]=>
      int(2)
      ["r"]=>
      int(1)
    }
    

    You could also condense things like this if you aren't scared off by regex:

    function count_char($str) {
        $letters = preg_split('~[^a-z]*~i', $str, -1, PREG_SPLIT_NO_EMPTY);
        if (!$letters) return [];
        $counts = array_count_values($letters);
        ksort($counters);
        return $counters;
    }
    
    var_dump(count_char("Hello World"));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?