2017-05-03 148 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