I have a multidimensional array that contains a variable number of sub arrays.
Each sub-array contains a list of numeric keys and values.
I have a separate array that is the result of an “array_intersect_key” function against the multidimensional array that contains only the keys that exist in each sub-array.
I want to walk through the intersect_key array and for each item in it sum the values associated with the matching keys within the multidimensional array and then take the total and use that to replace the value associated with the key in the intersect_key array while maintaining the same index id.
The key in each array relates to the id of an article in the database, the value associated with the key is how many times a certain word appears in that article. I’m trying to add together all the word counts relating to each article so I can then order them by relevance.
The code that creates the arrays:
$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);
I’ve started trying to tackle this by using the call_user_func_array() call again to branch out to a custom function but this approach doesn’t feel right.
Maybe replace
with
I suggest for performance, that you retrieve all required data with a single SQL query (maybe using
WHERE iws.keywordid IN (...)) and then process results in a PHP loop. Generally speaking, putting an SQL query in a loop should be avoided.EDIT suggestion: