如何解决为什么我的 PHP 脚本需要这么多时间?
我有一个用户表,目前有 6000 多个用户。
所有这些用户都有一个分数,我想在页面上显示它,或者理想情况下存储在一个视图中以便稍后显示。
如果我为所有 6000 个用户运行我的脚本,它甚至不会完成。
如果我为 200 个用户运行它,脚本大约需要 2 分钟才能运行,我不明白为什么要花这么长时间。
这是我的脚本:
//Create $i: the position counter
$i = 0;
//Create $j: ex aequo counter
$j = 1;
//Take all users from the db with their id and their score
//Currently limited to 100 because it went so slow
$sql = 'SELECT `id`,`score` FROM `gebruikers` ORDER BY `score` DESC LIMIT 100';
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
//If the current score is the same as the previous one (which has already been saved in $scoreboard[$i])...
if($scoreboard[$i]["Finds"] == $row['score']) {
// Then count how many in $j
$j++;
//Don't add up $i here,because we want to show ex aequo
} else {
//If not (so if the current score is different than the previous one),then add up the number of users that had the previous number to the position counter
$i = $i + $j;
//And set the ex aequo counter (back) to 1
$j = 1;
}
$scoreboard[$i]["Finds"] = $row['score'];
$scoreboard[$i]["IDs"][] = $row['id'];
}
结果应该是这样的:
Array
(
[1] => Array
(
[Finds] => 294
[IDs] => Array
(
[0] => 2087
)
)
[2] => Array
(
[Finds] => 289
[IDs] => Array
(
[0] => 227
[1] => 3934
)
)
[4] => Array
(
[Finds] => 284
[IDs] => Array
(
[0] => 192
)
)
[5] => Array
(
[Finds] => 279
[IDs] => Array
(
[0] => 4237
[1] => 4122
)
)
[7] => Array
(
[Finds] => 278
[IDs] => Array
(
[0] => 1999
)
)
etc...
*/
解决方法
您可以修改以分数为关键字的while循环代码。这将优化代码。
while ($row = $result->fetch_assoc()) {
$i = $row['score'];
$scoreboard[$i]["Finds"] = $row['score'];
$scoreboard[$i]["IDs"][] = $row['id'];
}
如果你想要 0,1,2 格式的键,你可以将 array_values 应用到记分板变量
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。