2016-03-07 65 views
1

我已搜索過去3天,但找不到解決方案。我試圖計算一個數組中玩家最低5分的總分,我嘗試過array_sum,但我無法讓它工作,不管我嘗試什麼,只顯示數組的5個最低值,但不會將它們加在一起,這裏是代碼。PHP mysqli計算數組結果的總數

<?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; 
      } 
+0

你的價值謝謝,我會嘗試,並獲得給予反饋表格。非常感謝您的幫助。 –

回答

0

您正在循環中的每次迭代中創建一個新數組。將元素添加到循環中的數組中,然後在循環完成後使用array_sum,或者將值添加到總和中。

E.g.

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

你也可以簡單地在你的SQL查詢中使用SUM()函數。這可能會更快。

+0

這工作完美,非常感謝你。 –

0

您可以在查詢中進行求和以節省處理時間並減少在數據庫和應用程序之間的傳輸。

基本上這應該做你想做的。我沒有親自測試過它,但它應該能夠在你的目標中減少邏輯障礙。

$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