开发者

Word & letter count in an associative array

I'm trying to learn some PHP, and I've been banging my head against this problem for hours. at this point, I'm pretty sure I've made it far more complicated than it ought to be (the last attempt I just scratched was ~100 lines long (admittedly, lots of comments).

Here's what I'm trying to do:

Read in a string, put the words in an associative array by number of letters, inside of which is an associative array of words, sorted alphabetically, and the number of times they appear.

The next problems in the series build on this one, so I'm basically dead in the water until I can f开发者_如何学JAVAigure this out.

Any suggestions?


$sample = "this my is sample which is simple";
$simple = explode(' ', $sample);

$words = array();
foreach ($simple as $word) {
   $size = strlen($word);
   if (!isset($words[$size])) {
      $words[$size] = array();
   }
   if (!isset($words[$size][$word])) {
      $words[$size][$word] = 0;
   }
   $words[$size][$word]++;
}
foreach ($words as &$w) {
   ksort($w);
}
ksort($words);

This is a bit nasty, but it gets the job done. Note that I reversed the first "my" and "is" to show the alphabetical reordering.


Assuming there is no punctuation to worry about try this:

$words_by_length = array();
$string = "this is my sample which is simple";
$words = explode(' ', $string); //split the string by space to find all the words
foreach($words as $word) {
    $word_length = strlen($word);

    if(!isset($words_by_length[$word_length])) $words_by_length[$word_length] = array();
    $words_by_length[$word_length][] = $word;
}

ksort($words_by_length);
foreach($words_by_length as $length => $words) {
    $words_by_freq = array();
    foreach($words as $word) {
        if(!isset($words_by_freq[$word])) $words_by_freq[$word] = 0;
        $words_by_freq[$word]++;
    }
    ksort($words_by_freq);
    $words_by_length[$length] = $words_by_freq;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜