使用php将数组转换为自定义格式
我有一个可以计算字符串中字母频率的代码。我的代码是:使用php将数组转换为自定义格式,php,arrays,Php,Arrays,我有一个可以计算字符串中字母频率的代码。我的代码是: <?php $str = "iamtheone"; $freq_count = array(); for ($i = 0; $i < strlen($str); $i++) { $index = $str[$i]; $freq_count[$index]++; foreach (range('a', 'z') as $char) {
<?php
$str = "iamtheone";
$freq_count = array();
for ($i = 0; $i < strlen($str); $i++) {
$index = $str[$i];
$freq_count[$index]++;
foreach (range('a', 'z') as $char) {
//echo "<pre>".$key . " " . $char."</pre>";
$index = $char;
if (isset($freq_count[$index])) {
} else {
$freq_count[$index] = "0";
}
}
}
echo "<pre>";
print_r($freq_count);
echo "</pre>";
?>
现在,我希望他们将数组转换为以下格式:
$str ="iamtheone";
// Calculate the frequency table for all letters
$letters = array_fill_keys(range('a', 'z'), ' ');
$freq_count = array_merge(
$letters,
array_count_values(str_split(strtolower($str)))
);
// Plot the display chart
for ($line = max($freq_count); $line > 0; --$line) {
echo implode(
' ',
array_map(
function ($value) use ($line) {
return ($value >= $line) ? '*' : ' ';
},
$freq_count
)
);
echo PHP_EOL;
}
echo implode(' ', array_keys($lineArray)), PHP_EOL;
说明:星号的数量取决于每个字母的频率。例如,a
在字符串中仅重复一次,e
在字符串中重复两次,依此类推
我的数组格式正确吗?有什么建议吗?谢谢以下是我的看法,只需在每个已发现的字符中添加一个星号,无需将出现的次数作为一个数字计算-也可以使用strtolower()转换大写字符并对其进行计数:
$freqCount=array();
$countedStr='iamstheone';
//初始化频率计数数组
foreach(范围('a','z')为$char){
$freqCount[$char]='';
}
因为($i=0;$i你的老师不会相信你在没有帮助的情况下做了这件事,但是:
您可以将所有现有代码简化为$str=“iamtheone”;$freq\u count=array\u merge(array\u fill\u key(范围('a','z'),0)、array\u count\u值(str\u split($str));var\u dump('freq\u count)
它的另一个优点是已经按字符排序了。非常感谢。这个代码对我来说是新的,现在学习起来很有趣。:-)米伦非常感谢。我现在就试试那个代码。
*
* * * * * * * *
a b c d e f g h i j k l m n o p q r s t u v w x y z
$freqCount = array();
$countedStr = 'iamtheone';
// inits the frequency count array
foreach (range('a','z') as $char) {
$freqCount[$char] = '';
}
for($i=0; $i<strlen($str); $i++) {
$index = $countedStr[$i];
// potentially convert to lower case:
// $index = strtolower($countedStr[$i]);
$freqCount[$index] .= '*'; // adds an asterisk to the letter
}
$str ="iamtheone";
// Calculate the frequency table for all letters
$letters = array_fill_keys(range('a', 'z'), ' ');
$freq_count = array_merge(
$letters,
array_count_values(str_split(strtolower($str)))
);
// Plot the display chart
for ($line = max($freq_count); $line > 0; --$line) {
echo implode(
' ',
array_map(
function ($value) use ($line) {
return ($value >= $line) ? '*' : ' ';
},
$freq_count
)
);
echo PHP_EOL;
}
echo implode(' ', array_keys($lineArray)), PHP_EOL;