我必须使用索引A-Z(字母表)创建一个数组。每个索引必须具有值0。 所以我做了这个数组:
$alfabet = array(
'A' => 0,
'B' => 0,
'C' => 0,
'D' => 0,
'E' => 0,
'F' => 0,
'G' => 0,
'H' => 0,
'I' => 0,
'J' => 0,
'K' => 0,
'L' => 0,
'M' => 0,
'N' => 0,
'O' => 0,
'P' => 0,
'Q' => 0,
'R' => 0,
'S' => 0,
'T' => 0,
'U' => 0,
'V' => 0,
'W' => 0,
'X' => 0,
'Y' => 0,
'Z' => 0
);
我也有文件中的文字($ text = file_get_contents('tekst15.txt');) 我已将该文件中的字符推送到数组:$ textChars = str_split($ text); 并从A-Z排序:sort($ textChars);
我想要的是(带有for循环)当他在textChars数组中找到A时,另一个带索引A的数组的值上升一个(如:$ alfabet [A] ++;
任何人都可以帮助我完成这个循环吗?我有这个atm:
for($i = 0; $i <= count($textChars); $i++){
while($textChars[$i] == $alfabet[A]){
$alfabet[A]++;
}
}
echo $alfabet[A];
问题1:我想将alfabet数组循环到,所以现在我只检查A但我想检查所有索引。 问题2:我现在为每个字母索引返回7我尝试完全错误:)
我很抱歉我的英语,但谢谢你的时间。
答案 0 :(得分:2)
听说 foreach
循环?
foreach ($textChars as $index => $value) {
$alfabet[$value]++;
}
答案 1 :(得分:0)
我假设您的$textChars
数组看起来像
$textChars = array (
0 => 'A',
1 => 'A',
2 => 'B',
);
如果是这样,你可以遍历它并使用它的值来检查$alfabet
中是否存在给定的索引,然后递增它。
foreach($textChars as $char){
if(isset($alfabet[$char])){
$alfabet[$char]++;
}
}
答案 2 :(得分:0)
count_chars()
功能可以立即为您提供该信息:
$stats = count_chars(file_get_contents('tekst15.txt'));
echo $stats['A']; // number of 'A' occurrences
echo $stats['O']; // number of 'O' occurrences
从你的代码:
while($textChars[$i] == $alfabet[A]){
$alfabet[A]++;
}
毫无意义;它将文本文件中的每个字符与$alfabet[A]
的值进行比较,最初为0
(甚至不是字母!)。
正确的陈述是:
$alfabet[$textChars[$i]]++;
答案 3 :(得分:0)
$fp = fopen('tekst15.txt', 'r');
if (!$fp) {
echo 'Could not open file tekst15.txt';
}
while (false !== ($char = fgetc($fp))) {
if(isset($alfabet[strtoupper($char)]))
{ $alfabet[strtoupper($char)] = $alfabet[strtoupper($char)]+1; }
}