对多维数组中具有相同索引ID的项的条目求和


Sum the entries of items with the same index ID in a multi-dimensional array?

我有一个多维数组,其中包含数量可变的子数组
每个子数组都包含一个数字键和值的列表
我有一个单独的数组,它是针对多维数组的"array_entersect_key"函数的结果,多维数组只包含每个子数组中存在的键。

我想遍历intersect_key数组,并对其中的每个项求和与多维数组中匹配关键字关联的值,然后取总数,并使用它来替换与intersect_key数组中关键字关联的数值,同时保持相同的索引id。

每个数组中的关键字与数据库中文章的id相关,与关键字相关的值是某个单词在该文章中出现的次数。我试着把每一篇文章的所有字数加在一起,这样我就可以按相关性排序了。

创建数组的代码:

$arr_articles = array();
foreach($arr_words as $wordid => $word) {
    $query = "SELECT articleid,wordcount FROM index_wordsearch AS iws WHERE iws.keywordid = '$wordid'";
    $articlesearch = mysql_query($query);
    if (!$articlesearch) {
        die('Unable to search for articles matching the specified words: '.mysql_error());
    } else {
        $arr_ids = array();
        while ($row = mysql_fetch_assoc($articlesearch)) {
            $articleid = $row['articleid'];
            $wordcount = $row['wordcount'];
            $arr_ids["$articleid"] = "$wordcount";
        }
        $arr_aticles[] = $arr_ids;
    }
}
$arr_matches = call_user_func_array('array_intersect_key',$arr_articles);

我已经开始尝试通过再次使用call_user_func_array()调用来分支到自定义函数来解决这个问题,但这种方法感觉不太好。

也许可以取代

$arr_ids["$articleid"] = "$wordcount";

带有

if (!isset($arr_ids[$articleid]))
  $arr_ids[$articleid] = 0;
$arr_ids[$articleid] += $wordcount;

为了提高性能,我建议您使用一个SQL查询(可能使用WHERE iws.keywordid IN (...))检索所有需要的数据,然后在PHP循环中处理结果。一般来说,应该避免将SQL查询放入循环中。

编辑建议:

$query = "SELECT articleid, SUM(wordcount) AS wordcount
  FROM index_wordsearch
  WHERE keywordid IN (".implode(", ", array_keys($arr_words)).")
  GROUP BY articleid";
$articlesearch = mysql_query($query) or die('Unable to search for articles matching the specified words: '.mysql_error());
$arr_articles = array();
 
while ($row = mysql_fetch_assoc($articlesearch))
    $arr_articles[$row['articleid']] = $row['wordcount'];
print_r($arr_articles); // shows total matched word count for each article id