2017-05-03 78 views
0

第一次使用php,我遇到了一些問題。 問題:在mysqli請求之後,我收到一個包含5列和多行的表的結果。我想用我剛剛收到的數據進行計算,並將我的calc的結果添加到我的數組中的NEW COLUMN中。 所以換句話說,我想向數組中添加一列,併爲每一行的結果填充此列。PHP - 將字段/列添加到數組

到目前爲止我的代碼如下所示,當然只打印,我從我的SQL查詢接收陣列:

<?php 
error_reporting(0); 
require 'init1.php'; 

if($result = $db->query("Select * from (select * from(SELECT * FROM `scores` 
ORDER BY `battle_id` ASC,user_id asc,score desc) as t1 GROUP BY 
t1.battle_id, t1.user_id) as t2 order by `battle_id` ASC,score desc")){ 

    if($count = $result->num_rows){ 

     echo '<p>' , $count, '<p>'; 

     while ($row = $result->fetch_object()){ 
      echo $row->battle_id, ' ' , $row->user_id, ' ' , $row->score, '<br>'; 
     } 
     //instead of just printing the existing array, I would like to perform a 
     //calculation and add a result in a new column at the end of every single 
     //row 
    } 
} 

?> 

非常感謝任何支持, 最好, 添

+0

你說的是什麼計算? –

+0

好吧,這有些複雜,但只是談論基本的數學。例如:新列中的任何新字段都應顯示結果(分數* 2 - 5)。 – gunjag

+2

'echo $ row-> score * 2 - 5;'簡單,不是嗎? –

回答

0

如果您使用Array可以簡單地在數組中定義一個新項目來存儲計算結果。

while ($row = $result->fetch_row()) { 
     // Calculation and other stuff here 
     $row['calc_result'] = $calculation_result; 
    } 

然後才能訪問它,而範圍之外,則需要每行存放在另一個數組,例如:

$stored_data = array(); 
while ($row = $result->fetch_row()) { 
    // Calculation and other stuff here 
    $row['calc_result'] = $calculation_result; 
    array_push($stored_data, $row); 
} 
+0

感謝您的提示,我打算使用一個數組並忘記將$ result-> fetch_object更改爲$ result-> fetch_row。修復。 :) –

+0

Thx再次,我現在有以下幾點: – gunjag