我想從字符串中的下列單詞中獲得字符的數量。例如,如果我輸入的是I am John
則輸出必須是這樣的:
如何在while循環中訂購?
9 // count of 'I am John'
4 // count of 'I am'
1 // count of 'I'
我用這樣的代碼在PHP這個過程:
$string = 'I am John';
$words = explode(' ',$string);
$count_words = count($words);
$i =0;
while ($i<$count_words){
if($i==0) {
$words_length[$i] = strlen($words[$i]);
} else {
$words_length[$i] = strlen($words[$i])+1+$words_length[$i-1];
}
echo $words_length[$i]."<br>";
$i++;
}
但它返回這樣的輸出:
1
4
9
爲什麼?我的錯誤在哪裏?我怎樣才能改變順序?
我的代碼必須是什麼樣的?
在此先感謝!
但它返回'陣列([0] => 6 [1] => 1 [2] => 4) ':( – John