警告:非法偏移类型错误

Warning : Illegal offset type error

此代码的第 $wordCountArr[$val]['bytotal'] = $wordCountArr[$val]['count'] / $totalWords; 行出现 "illegal offset type" 错误。这是代码,以防有人能提供帮助:

<?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));
?>

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

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

查看整个 foreach 循环:

将变量$wordCountArr改为$val:

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

希望对你有帮助。