dongqindan4406 2016-07-12 00:01
浏览 30
已采纳

在函数内添加新的数组键

I have an array that is populated by a mysql_fetch_assoc. After the array is populated by the columns I want from the database, I would like to add another key to the array, using values that I obtain earlier in the function. I tried to accomplish this with a foreach loop, but my function is not returning the array. Where have I gone wrong?

//calculates payout 
function calculate_payout($id){
    $result = mysql_query("SELECT `result` FROM `bets` WHERE `id` = {$id}");
    echo mysql_error();
    $wager_total = mysql_query("SELECT SUM(`wager_amount`) AS `wager_total` FROM `wagers` WHERE `id` = '{$id}'");
    $correct_wager_total = mysql_query("SELECT SUM(`wager_amount`) AS `correct_wager_total` FROM `wagers` WHERE `id` = '{$id}' AND `wager_option` = '{$result}'");
    echo mysql_error();
    $incorrect_wager_total = $wager_total - $correct_wager_total;

    $sql = "    SELECT * FROM `wagers` WHERE `id` = '{$id}' AND `wager_option` = '{$result}'";
    echo mysql_error();
    $data = mysql_query($sql);

    $rows = array();
    while(($row = mysql_fetch_assoc($data)) !== false){
        $rows[] = array(
            'bet_id'         => $row['bet_id'],
            'id'             => $row['id'],
            'wager_amount'   => $row['wager_amount']
        );
    }

    foreach ($rows as $p_row){
        $payout = $p_row['wager_amount'] / $incorrect_wager_total;
        $payout = $p_row['wager_amount'] + $payout;
        $p_row['payout'] = $payout;
    }

    return $p_row;
}
  • 写回答

1条回答 默认 最新

  • dongxieli3839 2016-07-12 00:16
    关注

    The problem is that $p_row is a copy of the row in the array, so modifying it in the loop doesn't have any effect on the original array.

    You can fix this by using a reference in the foreach:

    foreach ($rows as &$p_row)
    

    Or you can just do this as you're creating the $rows array in the while loop:

    while ($row = mysql_fetch_assoc($data)) {
        $new_row = array(
            'bet_id'         => $row['id'],
            'id'             => $row['id'],
            'wager_amount'   => $row['wager_amount'],
            'payout'         => $row['wager_amount'] / $incorrect_wager_total + $row['wager_amount']
        );    
    

    Also, your return statement is wrong, it should be return $rows; to return the whole array; return $p_row will just return the last row of the array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗