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

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能