警告:非法偏移类型错误

时间:2015-01-21 19:53:14

标签: php keyword

此代码的行$wordCountArr[$val]['bytotal'] = $wordCountArr[$val]['count'] / $totalWords;出现“非法偏移类型”错误。这是代码,以防任何人可以提供帮助:

<?php

function extractCommonWords($string)
{
  $stopWords = array('i','a','about','an','and','are','as','at','be','by','com','de','en','for','from','how','in','is','it','la','of','on','or','that','the','this','to','was','what','when','where','who','will','with','und','the','www');

  $string = preg_replace('/ss+/i', '', $string);
  $string = trim($string); // trim the string
  $string = preg_replace('/[^a-zA-Z0-9 -]/', '', $string); // only take alphanumerical characters, but keep the spaces and dashes too…
  $string = strtolower($string); // make it lowercase

  preg_match_all('/\b.*?\b/i', $string, $matchWords);
  $matchWords = $matchWords[0];

  $totalWords = count($matchWords[0]);

  foreach ( $matchWords as $key=>$item ) {
      if ( $item == '' || in_array(strtolower($item), $stopWords) || strlen($item) <= 3 ) {
          unset($matchWords[$key]);
      }
  }
  $wordCountArr = array();
  if ( is_array($matchWords) ) {
      foreach ( $matchWords as $key => $val ) {
          $val = strtolower($val);
          if ( !isset($wordCountArr[$val])) {
              $wordCountArr[$val] = array();
          }
          if ( isset($wordCountArr[$val]['count']) ) {
              $wordCountArr[$val]['count']++;
          } else {
              $wordCountArr[$val]['count'] = 1;
          }
      }
      arsort($wordCountArr);
      $wordCountArr = array_slice($wordCountArr, 0, 10);
      foreach ( $wordCountArr as $key => $val) {
          $wordCountArr[$val]['bytotal'] = $wordCountArr[$val]['count'] / $totalWords;
      } 
  }
  return $wordCountArr;
}

$text = "AES algo to encrypt files.";
$words = extractCommonWords($text);
echo implode(',', array_keys($words));
?>

2 个答案:

答案 0 :(得分:2)

查看整个foreach循环:

将变量$wordCountArr更改为$val

foreach ( $wordCountArr as $key => $val) {
      $val['bytotal'] = $val['count'] / $totalWords;
  }

希望它对你有所帮助。

答案 1 :(得分:1)

你应该在最后的foreach循环中使用$ key而不是$ val。

foreach ( $wordCountArr as $key => $val) {
   $wordCountArr[$key]['bytotal'] = $wordCountArr[$key]['count'] / $totalWords;
}