You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计嵌套数组Query字段中所有字符串的唯一词频?

Fixing the Word Frequency Count for All Query Fields

The main issue with your current code is that you’re not maintaining a running total of word counts across all nested arrays—you’re only processing one entry at a time without accumulating the results. Here’s how to adjust it to tally counts from every Query value:

// Initialize an empty array to hold our total word counts
$totalWordCounts = [];

// Loop through each nested array in the main data array
foreach ($data as $item) {
    // Make sure the "Query" key exists to avoid PHP errors
    if (isset($item['Query'])) {
        // Split the Query string into individual words
        $words = explode(' ', $item['Query']);
        
        // Get word counts for this specific Query entry
        $currentCounts = array_count_values($words);
        
        // Merge these counts into our running total
        foreach ($currentCounts as $word => $count) {
            if (isset($totalWordCounts[$word])) {
                // If the word already exists, add the current count to the total
                $totalWordCounts[$word] += $count;
            } else {
                // If it's a new word, set its count to the current value
                $totalWordCounts[$word] = $count;
            }
        }
    }
}

// Output the final accumulated counts
print_r($totalWordCounts);

Key Improvements:

  • Running Total Array: We start with $totalWordCounts to persist counts across all nested arrays, instead of resetting or ignoring previous entries.
  • Direct Query Access: Instead of looping through all keys in each nested array, we directly access $item['Query'] (with a safety check to avoid errors if any entry lacks the Query key).
  • Count Accumulation: For each Query's word list, we add its counts to the total—either incrementing existing entries or adding new ones as needed.

When you run this with your sample input, you’ll get the expected result:

Array
(
    [hehe] => 2
    [haha] => 1
    [hihi] => 1
    [hoho] => 1
    [hrooo] => 1
)

Bonus: Concise Functional Approach

If you prefer a more streamlined style, you can use array_reduce to handle the accumulation in a single function call (though the loop version is easier to follow for beginners):

$totalWordCounts = array_reduce($data, function($carry, $item) {
    if (!isset($item['Query'])) return $carry;
    $currentCounts = array_count_values(explode(' ', $item['Query']));
    foreach ($currentCounts as $word => $count) {
        $carry[$word] = ($carry[$word] ?? 0) + $count;
    }
    return $carry;
}, []);

print_r($totalWordCounts);

This achieves the same result but wraps the logic in a reducer function. The ?? 0 operator safely handles cases where the word isn’t yet in the running total.

内容的提问来源于stack exchange,提问作者hrca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:30:38