我有一个由mysql_fetch_assoc填充的数组。在我希望从数据库填充数组之后,我想使用我之前在函数中获得的值向数组中添加另一个键。我尝试使用foreach循环完成此操作,但我的函数没有返回数组。我哪里出错?
//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;
}
答案 0 :(得分:1)
问题是$p_row
是数组中行的副本,因此在循环中修改它对原始数组没有任何影响。
您可以使用foreach
:
foreach ($rows as &$p_row)
或者您可以在$rows
循环中创建while
数组时执行此操作:
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']
);
另外,你的return语句是错误的,它应该是return $rows;
来返回整个数组; return $p_row
将返回数组的最后一行。