gpt4 book ai didi

php - 在 PHP 中对数组进行排序与​​从 SQL 中获取数据

转载 作者:太空宇宙 更新时间:2023-11-03 10:45:21 26 4
gpt4 key购买 nike

我正在使用以下 php 方法查找数组中出现次数最多的 10 个元素,然后返回一个包含这 10 个元素及其出现次数的新数组。这对于相当小的阵列来说很好。但我从数据库中获取数据,数组的大小很容易超过 100000。这导致此方法非常慢。代码如下:

function getTopTenSelects($array) {
$result = [];
for ($x = 0; $x <= 10; $x++) {
$count = countArray($array);
$mostOccuring = (key($count));
$arrayReturn[$x] = $mostOccuring;
array_push($result, [$mostOccuring,$count[$mostOccuring]]);
foreach ($array as $temp) {
if (($key = array_search($mostOccuring, $array)) !== false) {
// Cuts the key from the array foreach time it appears so we can find the next most occuring value
unset($array[$key]);
}
}
}
return $result;
}

现在。我通过以下 SQL 查询获取我的数组。 $hashtag 是一个包含一段字符串的变量。

SELECT tag_names
FROM soc_stat
JOIN tags on soc_stat.insta_id = tags.insta_id
WHERE main_tag = $hashtag

在 php 中是否有一种有效的方法,或者是否有一种方法可以通过 SQL 查询获得我需要的东西?

最佳答案

当然,为了进行少量数据交换,您应该只从数据库中检索真正需要的数据。在您的例子中,前 10 个标签名称:

SELECT tag_names, count(*)
FROM soc_stat
JOIN tags on soc_stat.insta_id = tags.insta_id
WHERE main_tag = $hashtag
group by tag_names
order by count(*) desc limit 10;

关于php - 在 PHP 中对数组进行排序与​​从 SQL 中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32738534/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com