在PHP中读取相应的值并添加到运行总和

时间:2012-01-05 05:45:39

标签: php arrays string file-get-contents running-total

我希望在文件中交叉引用字符串中的每个单词。

所以,如果给我字符串:Jumping jacks wake me up in the morning.

  1. 我使用一些正则表达式去除期间。此外,整个字符串都是小写的。
  2. 然后我继续使用PHP的漂亮explode()函数将单词分成数组。
  3. 现在,我剩下的是一个包含字符串中使用的单词的数组。
  4. 从那里我需要查找数组中的每个值并获取它的值并将其添加到运行总和中。 for()循环它。好的,这是我被卡住的地方......

    列表($wordlist)的结构如下:

    wake#4 waking#3 0.125

    morning#2 -0.125

    单词和数字之间有\t个。 可以每个值超过一个单词。

    我现在需要PHP做的是查找数组中每个单词的数字,然后将相应的数字拉回以将其添加到运行总和中。对我来说,最好的方法是什么?

    答案应该很简单,只需在wordlist中找到字符串的位置,然后找到标签,然后从那里读取int ...我只需要一些指导。

    提前致谢。

    编辑:澄清 - 我不想要单词列表的值的总和,而是,我想查找我的个别值,因为它们对应于单词中的单词然后在列表中查找它们并添加这些值;不是全部。

2 个答案:

答案 0 :(得分:1)

根据您的评论和问题编辑编辑回答。运行总和存储在名为$ sum的数组中,其中“word”的键值将存储其运行总和的值。例如$ sum ['wake']将存储单词wake的运行总和,依此类推。

$sum = array();
foreach($wordlist as $word) //Loop through each word in wordlist
{
    // Getting the value for the word by matching pattern.
    //The number value for each word is stored in an array $word_values, where the key is the word and value is the value for that word.
    // The word is got by matching upto '#'. The first parenthesis matches the word - (\w+)
    //The word is followed by #, single digit(\d), multiple spaces(\s+), then the number value(\S+ matches the rest of the non-space characters)
    //The second parenthesis matches the number value for the word

    preg_match('/(\w+)#\d\s+(\S+)/', $word, $match);  
    $word_ref = $match[1];
    $word_ref_number = $match[2];
    $word_values["$word_ref"] = $word_ref_number;

}

//Assuming $sentence_array to store the array of words used in your string example {"Jumping", "jacks", "wake", "me", "up", "in", "the", "morning"}

foreach ($sentence_array as $word)
{
    if (!array_key_exists("$word", $sum)) $sum["$word"] = 0;
    $sum["$word"] += $word_values["$word"]; 
}

我假设您会处理案例敏感性,因为您提到您将整个字符串设为小写,因此我不在此处。

答案 1 :(得分:0)

$sentence = 'Jumping jacks wake me up in the morning';

$words=array();

foreach( explode(' ',$sentence) as $w ){

  if( !array_key_exists($w,$words) ){

   $words[$w]++;

  } else {
    $words[$w]=1;
  }

}

爆炸空间,检查单词数组中的单词是否为;如果这样增加它的计数( val );如果没有,将它的val设置为1.为每个句子循环这个而不重新声明$ words = array()