我试图在数组中首先使用大写字母按字母顺序对数组进行排序
示例:
array(7) {
["H"]=>
int(1)
["W"]=>
int(1)
["e"]=>
int(1)
["l"]=>
int(3)
["o"]=>
int(2)
["r"]=>
int(1)
["d"]=>
int(1)
}
我的代码不是按大写字母排序,只是按字母顺序排序
这是我的代码:
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"));
我想要的输出是$ str,我想按字母顺序排列鞋面,然后按字母顺序降低
答案 0 :(得分:2)
就我个人而言,我会这样做:
<?php
$str = "Hello World";
// split the string (ignoring spaces)
$array = str_split(str_replace(' ', '', $str), 1);
// count the chars
$array = array_count_values($array);
// sort naturally
array_multisort(array_keys($array), SORT_NATURAL, $array);
print_r($array);
<强>结果:强>
Array
(
[H] => 1
[W] => 1
[d] => 1
[e] => 1
[l] => 3
[o] => 2
[r] => 1
)
编辑:如果您想按值排序,然后按键排序:
<?php
$str = "Hello World";
// split the string (ignoring spaces)
$array = str_split(str_replace(' ', '', $str), 1);
// count the chars
$array = array_count_values($array);
// get the keys
$keys = array_keys($array);
// sort my keys
array_multisort($array, $keys);
// combine sorted keys with array
$array = array_combine($keys, $array);
print_r($array);
<强>结果:强>
Array
(
[H] => 1
[W] => 1
[d] => 1
[e] => 1
[r] => 1
[o] => 2
[l] => 3
)
答案 1 :(得分:1)
ksort()
会这样做。您应该只调用ord()
一次,然后只存储结果以最小化函数调用。 ...或者更好的只是致电ctype_alpha()
以确保您只存储信件。我建议添加花括号以提高可读性。
代码:(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"));
输出:
array(7) {
["H"]=>
int(1)
["W"]=>
int(1)
["d"]=>
int(1)
["e"]=>
int(1)
["l"]=>
int(3)
["o"]=>
int(2)
["r"]=>
int(1)
}
如果你没有被正则表达式吓跑,你可以也压缩这样的事情:
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"));