PHP - 将字段/列添加到数组

时间:2017-05-03 20:20:46

标签: php multidimensional-array

第一次使用php,我遇到了一些问题。 问题:在mysqli请求之后,我收到一个包含5列和多行的表的结果。我想用我刚刚收到的数据进行计算,并将我的计算结果添加到我的数组中的新列中。 所以换句话说,我想在数组中添加一列,并在每列中填入结果。

我的代码到目前为止看起来如下,当然只打印我从我的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   
    }
}

?>

非常感谢任何支持, 最好, 蒂姆

1 个答案:

答案 0 :(得分:0)

如果你使用数组,你可以简单地定义&#39;数组中的新项目,用于存储计算结果。

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

然后,为了在while范围之外访问它,您需要将每一行存储在另一个数组中,例如:

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