【问题标题】:PHP mysqli Calculating total of array resultsPHP mysqli 计算数组结果的总数
【发布时间】:2016-03-07 21:15:45
【问题描述】:

我已经搜索了过去 3 天,但找不到解决方案。我正在尝试计算数组中玩家的最低 5 分的总分,我尝试了 array_sum 但我无法让它工作,无论我尝试什么,它只显示数组的 5 个最低值,但没有将它们加在一起,这是代码。

<?php
if (isset($_POST['calc'])) {

    $player = $_SESSION['id'];

    $result = $conn->query("SELECT * FROM scores WHERE player_id='$player' ORDER by points ASC");

    $row = $result->fetch_array();
    $row_count = mysqli_num_rows($result);

    if ($row_count>=10) { // checks that at least 10 rows available
        $result = $conn->query("SELECT points FROM scores WHERE player_id='$player' ORDER by points ASC LIMIT 5"); // select 5 lowest points
            while ($row = mysqli_fetch_array($result)) {
                $total = array($row['points']);
                $sum = array_sum($total);
                echo $sum;
            }   

【问题讨论】:

  • 谢谢,我会尽快尝试并得到反馈。非常感谢您的帮助。

标签: php arrays mysqli


【解决方案1】:

您正在循环的每次迭代中创建一个新数组。要么将元素添加到循环中的数组,然后在循环完成后使用 array_sum,要么简单地将值添加到总和中。

例如

$sum = 0;
while ($row = mysqli_fetch_array($result)) {
   $sum += $row['points'];
}
echo $sum;

您也可以在 SQL 查询中简单地使用 SUM() 函数。这可能更快。

【讨论】:

    【解决方案2】:

    您可能可以在查询中进行求和,以节省自己的处理时间并减少在数据库和应用程序之间传输的时间。

    基本上这应该做你想要的。我没有亲自测试过它,但它应该可以在你的逻辑障碍更少的情况下工作。

    $total = 0;
    $result = $conn->query("SELECT count(points) as total FROM scores WHERE player_id='$player' ORDER by points ASC");
    
    $row = $result->fetch_array();
    if($row['total'] >= 10)
    {
      $result = $conn->query("SELECT sum(points) as SumPoints FROM scores WHERE player_id='$player' ORDER by points ASC LIMIT 5");
      $row = $result->fetch_array();
      $total = $row['SumPoints'];
    }
    

    你在$total中拥有你的价值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多