在我的 SQL 数据库中有一个包含数组的列。每个数组由许多数组组成
["word",NUMBER]
如示例 $rowOne、$rowTwo、$rowThree 所示。数组的长度和字可以不同。我用 NLTK 分析了很多文本。现在我想组合一个类别的所有文本,以获得例如一个类别中最常见的单词。
$rowOne = [('love', 14), ('let', 12), ('rain', 12), ('yea', 7), ('oh', 7), ('make', 5), ('happy', 3), ('dream', 3)];
$rowTwo =[('la', 12), ('high', 10), ('fun', 6), ('sun', 6), ('two', 5), ('fly', 5), ('one', 5), ('bridge', 4)];
$rowThree = [('deal', 33), ('ya', 19), ('gotta', 7), ('know', 6), ('another', 5), ('take', 5), ('thrill', 4), ('get', 4)];
目的是获取我的 WebApp 用户想要的所有 $rows(通常可以是数千行),并将所有数组合并到一个按 Number 排序的 $result 数组,
我现在的方法是构建一个 $combinedArray 和如此长的行来组合现有的函数 mergeTwoArrays 将一个 rowArray 集成到 $combinedArray 中。 但我对这个解决方案和性能非常不满意,因为数组不断增长......
function combineTwoArray ($combinedArray, $arrayToCombine)
{
$result = $combinedArray;
foreach ($combinedArray as $element) {
foreach ($arrayToCombine as $combineElement) {
if($element[0] == $combineElement[0]{
$number = $element[1] + $combineElement[1];
$word = $element[0];
$array = [$word,$number]
array_push($result, $array);
}
}
return $result;
}
我希望有更好更快的解决方案...!! :/
每一行都有一个唯一的歌曲 ID,一种更好的方法可能是创建一个新表。
- 我可以识别具有 id 的行
- 但是我应该如何分割我的数组...?!?!对于每个数组位置('love',14)一个新列或数字也分开?
我尝试构建一个 SQLFiddle,但我认为它不起作用。 SQLFiddle
最佳答案
我不会费心合并数组。 像 arilia 已经提到的那样,创建一个包含单词和计数的专用表会更快更容易。 所以表格看起来像这样:
song_id word word_count
1 hello 20
2 bye 3
然后你可以使用sql函数sum来求和,如下所示:
select *, sum(word_count)
from tablename
group by word
如果您想进一步过滤结果,例如仅查找特定歌曲中的单词数,您可以查询:
select * sum(word_count)
from tablename
where song_id in (<ids of the songs you want to search for>)
group by word
关于php - SQL 数组列;合并所有数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36155749/