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 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)